如何管道进入第三个流程?

时间:2016-01-28 07:55:04

标签: c unix system

这就是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>

char* reverseString(char*);

int main(void)
{
    pid_t id;
    int fd[2], nbytes;
    char string[80];
    char readbuffer[80];
    char* reversed;
    pipe(fd);

    if((id = fork()) == -1)
    {
        perror("fork");
        exit(1);
    }
    if(id != 0)
    {
        close(fd[0]);
        printf("PARENT\n--------------------\n");
        // printf("fork: %d\n", id);
        printf("my pid is %d\n", getpid());
        // printf("my parent's pid is %d\n", getppid());
        printf("enter string: ");
        scanf("%s", string);
        write(fd[1], string, (strlen(string)+1));

    }
    else
    {
        close(fd[1]);
        printf("CHILD\n--------------------\n");
        // printf("fork: %d\n", id);
        printf("my pid is %d\n", getpid());
        // printf("my parent's pid is %d\n", getppid());
        nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
        printf("Received string: %s\n", readbuffer);
        reversed = reverseString(readbuffer);
        printf("Reversed string: %s\n", reversed);

        pid_t id2;
        int fd2[2];
        char readbuffer2[80];

        pipe(fd2);

        if((id2 = fork()) != 0)
        {
            close(fd2[0]);
            printf("My pid: %d\n", getpid());
            write(fd2[1], reversed, (strlen(reversed)+1));
        }
        else
        {
            close(fd2[1]);
            printf("My Child's PID: %d\n", getpid());
            nbytes = read(fd2[0], readbuffer2, sizeof(readbuffer2));
            printf("Received string2: %s\n", readbuffer2);
        }

    }
    return (0);
}

char* reverseString(char* str)
{
    char reversed[80];
    int n = strlen(str);
    for(int i = n - 1, j = 0; i >= 0; i--, j++)
        reversed[j] = str[i];
    reversed[n] = '\0';
    return reversed;
}

我正在尝试将反向字符串传递到第二个进程中分叉的第三个进程,但它没有显示出来。

此外,当我在输入后执行scanf时,打印一直持续到打印子部件,然后输入字符串。如何防止打印所有内容。它看起来像这样:

PARENT
--------------------
my pid is 821
enter string: CHILD
--------------------
my pid is 822
$

1 个答案:

答案 0 :(得分:3)

reverseString函数中,您将返回一个自动局部变量的数组地址。当函数返回时,这些变量会被破坏。

char* reverseString(char* str)
{
    char reversed[80];
    // local array, cannot use it after the function returns

使用malloc()分配将在函数调用之间保留的内存,或者将字符串反转到原位。