#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