So this is simple program of creating two process: parent and child. So what I did is have the greeting inside the parent and the name inside the child process. For some reason my child process is not printing despite that I called wait() inside the parent. What should I do?
GOAL OUTPUT: "Hello Sam" OUTPUT I"M GETTING: "Hello"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
char *greeting = "Hello";
char *name;
pid_t pid;
pid = fork();
if(pid == 0)
{
name = "Sam";
exit(0);
}
else if(pid == -1)
printf("Fail\n");
else{
wait(0);
printf("%s %s", greeting, name);
}
}
When you make a call to fork(), the child process will receive a copy of the parent process' address space (variables etc...). This means that in the child, "name" is defined, from the parent. However, "name" in the child process is just a copy. So modifying it in the child process does not affect the parent.
To get the behavior that I sense you're after, replace fork() with vfork(). For the purposes of this discussion, the only difference is that:
Edit: I forgot to add that if you go the vfork route, change exit() to _exit() in the child process
Child process once forked will run independantly of the parent process. So when you set name="Sam"
in child it is in different program, than the printf. So you are not able to see the message.
In the child process, you assigned to name
and then exit.
if(pid == 0)
{
name = "Sam";
exit(0);
}
The printf("%s %s", greeting, name);
line is executed only in the else
branch, ie, the parent process. It's actually undefined behavior because name
is uninitliazed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.