开发者

fork() doesn't execute child process code

开发者 https://www.devze.com 2023-03-13 17:00 出处:网络
I am new to fork() and I\'m trying to figure out how is it possible that the program,开发者_Python百科 you see below, doesn\'t execute the code of the child process. Will you please help me understand

I am new to fork() and I'm trying to figure out how is it possible that the program,开发者_Python百科 you see below, doesn't execute the code of the child process. Will you please help me understand what's going on?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int glob = 1;

int main(int argc, char *argv[])
{
int local = 1;
int *dyn, pid;
char *myName = "parent";
dyn = (int *) malloc (sizeof(int));
*dyn = 1;

printf("Here it is how fork() works\n");
if ((pid = fork()) < 0)
{
    printf("Error.\n");
    exit(1);
}

printf("pid: %d", pid);
if (pid)
{
    sleep(1);
}
else
{
    glob = 2;
    local = 2;
    *dyn = 2;
    *myName = "child";
    printf("I'm the child!");
}
printf("[[ %s ]]\n glob=%d\n local=%d\n *dyn=%d\n", myName, glob, local, *dyn);
exit(0);
 }


You child process is most likely killed by a segmentation fault:

*myName = "child";

is invalid as your compiler should have told you (if it didn't warn on that, please turn up the warnings/diagnostics level).

If you wanted to change myName, you'd need to use something like strcpy. But you can't do that on myName because it could point to read-only memory. You should initialize it with dynamic memory like you do for the dyn pointer.

If all you need is that myName points to a different string, you can use:

myName = "child";


remove the '*' before myName.

myName = "child";
0

精彩评论

暂无评论...
验证码 换一张
取 消