开发者

How to sync processes inside a while loop in c

开发者 https://www.devze.com 2023-02-26 07:23 出处:网络
I am experiencing quite a dilemma: I have the following program structure: char* input = (char *)malloc(sizeof(char));

I am experiencing quite a dilemma:

I have the following program structure:

char* input = (char *)malloc(sizeof(char));
input = "CONTINUE";

while(strcmp(input, "EXIT") != 0 )
{
    printf("%s", "prompt: ");
    scanf("%s", input);

    if( strcmp(input, "test") == 0 )
    {
        pid_t childPid;
        switch(childPid = fork())
        {
            case -1:
                printf("%s", "Error");
                break;
            case 0:
                foo(input);
                break;
        }
    }
    else if(/.../)
    {
    }
    else
    {
        input = "EXIT";
    }

}

void foo(char* input)
{
   printf("%s %s", "printing" input);
}

So the pro开发者_StackOverflowblem is that when the loop executes it prints "prompt: " the first time, then it prints "prompt: " again, and finally the child process from the if statement prints its output.

It's like the child processes are out of sync or something and i can't figure out what is causing that extra "prompt: " to be printed the second time. This is a sample output:

prompt: test                  //typed "test"
prompt:                       //Where is this comming from?
printing test
prompt:                       //new iteration of loop expecting input


fork() causes a child process to be created as an exact copy of the parent, but also allows the parent to continue executing.

Your code does nothing in the parent when it successfully spawns a child (fork returns a number greater than 0, indicating the child's process ID; that return is not handled by your switch). Thus, the parent returns to the beginning of the while loop and prints "prompt" again.

The child calls foo (fork returns 0), but after that your code simply does a break from the switch statement. After that point, the child follows the exact same code path as the parent, so it also prints "prompt" and then does a scanf.

What you want to do is probably something more along these lines:

childPid = fork();
if (childPid < 0)
{
    perror("fork()");
}
else if (childPid == 0)
{
    foo(input);
    exit(0); // terminate the child process
}
else
{
    waitpid(childPid, NULL, 0); // suspend the parent until the child exits
}

Since you're printfing from both processes, you probably want to suspend the parent until the child has completed (using waitpid). Otherwise the "prompt" will likely get printed before the output from foo(). On some platforms the prints can happen at the same time resulting in intermixed characters or completely garbled terminal output.

0

精彩评论

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