LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Hi, I ran this following code...... need help on this. (https://www.linuxquestions.org/questions/programming-9/hi-i-ran-this-following-code-need-help-on-this-674630/)

LinuxInfo 10-06-2008 02:26 PM

Hi, I ran this following code...... need help on this.
 
Respected Sir,

I tired the following code:

#include<stdio.h>
int main()
{
int i;
i = fork();
if (i > 0)
{
wait(i); /*will wait for child*/
printf("%d%s", i, " This is child");
}
else if(i == 0)
{
wait(getppid()); /*will wait for parent*/
printf("child process");
}
return 0;
}

Here, according to the code, this shold never give any output because both parent and child should wait for each other. However, they are not waiting and printing outputs immediately. Could you please let me know why its happening like this?

Thanks.

Hko 10-06-2008 03:01 PM

AFAICT wait() can only be used on child processes.

Apart from that, you should have included the proper header files (unistd.h, sys/types.h and sys/wait.h) and used the proper type for PID's (not 'int' but 'pid_t').

Then the compiler would have complained with an error telling you there was something wrong with the first argument of wait(). You could then have looked up the man page of wait(2) and see that you used wait() the wrong way.

wait() can be called in two ways:
Code:

pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);

So, if you call wait() with one argument, it needs to be a pointer-to-int (then wait() will write the status to the int). Not a pid_t and not an int.

If want to call wait() with a PID (pid_t type) you need to give 3 arguments.

And also the man page says it assumes to be waiting for child processes only.


All times are GMT -5. The time now is 05:28 AM.