Reputation: 1097
#include <stdio.h>
#include <unistd.h>
int main(void)
{
FILE *fp;
int pid;
char msg1[] = "Test 1 2 3 ..\n";
char msg2[] = "Hello, hello\n";
if ((fp = fopen("testfile2", "w")) == NULL) // create the file
return 0;
fprintf(fp, "%d: %s", getpid(), msg1); // parent print the message1
if ((pid = fork()) == -1) // I fork a child process
return 0;
fprintf(fp, "%d: %s", getpid(), msg2); // both parent and child print
fclose(fp); // and close
return 1;
}
Here's the content of the "testfile2":
6969: Test 1 2 3 ..
6969: Hello, hello
6969: Test 1 2 3 ..
6970: Hello, hello
Upvotes: 1
Views: 94
Reputation: 5548
You are not using fork()
correctly and your if tags are not enclosed.
#include <sys/types.h> /* pid_t */#include <sys/wait.h> /* waitpid */#include <stdio.h> /* printf, perror */#include <stdlib.h> /* exit */#include <unistd.h> /* _exit, fork */
int main(void)
{
pid_t pid = fork();
if (pid == -1) {
// When fork() returns -1, an error happened.
perror("fork failed");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
// When fork() returns 0, we are in the child process.
printf("Hello from the child process!\n");
_exit(EXIT_SUCCESS); // exit() is unreliable here, so _exit must be used
}
else {
// When fork() returns a positive number, we are in the parent process
// and the return value is the PID of the newly created child process.
int status;
(void)waitpid(pid, &status, 0);
}
return EXIT_SUCCESS;
}
Example from : http://en.m.wikipedia.org/wiki/Fork_(system_call)#Example_in_C
Upvotes: 1
Reputation: 13957
Let me guess: you would expect the output to be
6969: Test 1 2 3 ..
6969: Hello, hello
6970: Hello, hello
Right? So why isn't it like this? Well, I guess that the output of
fprintf(fp, "%d: %s", getpid(), msg1);
has not been flushed to the file at the point of time, when fork()
is executed. So the output buffer is copied as well and that contains still
6969: Test 1 2 3 ..
So finally you what you got ;) I think this could be different, if you call fflush(fp);
after the first printff(...)
.
Check this nice SO post as well ...
Upvotes: 2