Code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int
main (int argvc, char *argv[])
{
pid_t pid;
int arg1 = atoi(argv[1]);
pid = fork();
if (pid == 0) {
printf("I am child\n");
printf("my pid is: %d\n", getpid());
printf("my parent pid is: %d\n", getppid());
printf("I am changing argument from %d ", arg1);
arg1 *= 2;
printf(" to %d\n", arg1);
}
else {
printf("I am a parent\n");
printf("my pid is: %d\n", getpid());
printf("my child pid is: %d\n", pid);
printf("The argument passed to me is %d\n", arg1);
}
/* This code executes in both processes */
printf("exiting ... %d\n", getpid());
exit(0);
}
argument. (So if the program was called as “./a.out 10” the parent prints 10 for argument, child prints 10 and 20; and the grandchild prints 20 and 40 as the argument value.) I can't quite figure out what I'm doing wrong though. Any help would be greatly appreciated btw...I'm using gcc to compile this code in cygwin.
Code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
int
main (int argvc, char *argv[])
{
/* parent process created */
pid_t pid;
int arg1 = atoi(argv[1]);
/* child process created */
if ((pid = fork()) < 0) {
perror("fork");
exit(1);
}
if (pid == 0) {
/* grandchild process created */
if ((pid = fork()) < 0) {
perror("fork");
exit(1);
}
printf("I am child\n");
printf("my pid is: %d\n", getpid());
printf("my parent pid is: %d\n", getppid());
printf("I am changing argument from %d ", arg1);
arg1 *= 2;
printf(" to %d\n", arg1);
printf("I am grandchild\n");
printf("my pid is: %d\n", getpid());
printf("my parent pid is: %d\n", getppid());
printf("I am changing argument from %d ", arg1);
arg1 *= 2;
printf(" to %d\n", arg1);
exit(1);
wait(1);
}
else {
printf("I am a parent\n");
printf("my pid is: %d\n", getpid());
printf("my child pid is: %d\n", pid);
printf("The argument passed to me is %d\n", arg1);
}
while (pid != wait (0));
printf ("Parent: Child %ld terminated\n", pid);
close (*argv[1]);
printf ("Parent: Killing Grand Child %ld\n", pid);
kill (pid, SIGTERM);
/* This code executes in both processes */
printf("exiting ... %d\n", getpid());
exit(0);
}