Reputation: 2013
So i've been reading posts on StackOverflow and the fork man-page and I just don't get the behavior I see, probably because I'm only looking for what I expect.
Its a simple program that takes a file name, spawns a child, runs stat() on the file, then returns SIGUSR1 or 2 back to the parent in a loop. The parent just wants to know if its 1 or 2... What I get, is "User defined signal 2" and then the program exits. But the parent is in a while loop right?
Anyway I was really hoping someone could explain why I'm not getting the expected output, specifically, the loop to continually ask for a file-name and spawn a child each time and the parent to know what signal the child returns with kill().
pid_t pid;
while(1) {
if(pid == 0) // i am the child
{
FILE *fp = fopen(fname, "r");
if(fp == NULL){
printf("%d] Child cannot find [%s].", msg++, fname);
fclose(fp);
}
else {
stat(fname, &st);
n = st.st_size;
printf("%d] Child read %d chars.\n", msg++, n);
if(n%2) kill(pid, SIGUSR1);
else kill(pid, SIGUSR2);
}
}
else // im the parent
{
if( signal(SIGUSR1,NULL) ) // Code never gets here because it ends
printf("%s is odd\n", fname );
if( signal(SIGUSR2, NULL) )
printf("$s is even\n", fname );
printf("%d] Enter filenames until you're happy. 'die' to end.\n", msg++);
scanf("%s", fname);
pid = fork();
}
}
return 0;
Upvotes: 3
Views: 403
Reputation: 3045
In the child the pid
is zero
, fork
returns child pid to parent, but child gets zero
, and u r trying to kill a process with pid 0, but pid of init is 1
, u can use getpid()
to get the current pid
of the child
. and then try to signal it.
Edit:
And also, pid
is un initialized when the loop enters first time, which may also result in undefined behavior. Thanks @Giresh
Upvotes: 4