Reputation: 2343
As code , why I don't get any outputs , can anybody tell me the issue? like that I have two fork()
and each will run in a child process and my parent process will not be exit, seems right, but still don't get anything output.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
/***********************************/
printf("--beginning of program\n");
int counter = 0;
pid_t pid1 = 0;
pid_t pid2 = 0;
while(1){
if(pid1 == 0)
pid1 = fork1();
if(pid2 == 0)
pid2 = fork2();
}
printf("--end of program--\n");
return 0;
}
/* Two fork() */
pid_t fork1(){
pid_t pid = fork();
if(pid ==0 )
{
while(1){
sleep(1);
fprintf(stdout," fork1 ");
}
}
return pid;
}
pid_t fork2(){
pid_t pid = fork();
if(pid ==0 )
{
while(1){
sleep(1);
fprintf(stdout," fork1 ");
}
}
return pid;
}
Upvotes: 0
Views: 67
Reputation: 226
stdout is buffered, it will normally only be flushed on a newline or if you explicitly flush it.
You can get your code to output the lines from the children processes by adding a newline in your statements:
fprintf(stdout, "fork1\n");
Or by explicitly flushing the buffer after the fprintf:
fflush(stdout);
Upvotes: 2