0

我得到了一些奇怪的输出:

Read 0 bytes: P
?\?  

从我的代码:

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

char phrase[0] = "stuff this in your pipe and smoke it";
int main(int argc, char* argv[]) {
    int fd[2], bytesRead;
    char message[100];
    int pid;
    pid = fork();
    pipe(fd);
    if (pid == 0) {
        close(fd[0]);
        write(fd[1], phrase, strlen(phrase) + 1);
        close(fd[1]);
    }else {
        close(fd[1]);
        bytesRead = read(fd[0], message, 100);
        printf("Read %d bytes: %s\n", bytesRead, message);
        close(fd[0]);

    }
}

我不知道我哪里出错了,知道吗?

4

2 回答 2

2
pid = fork();
pipe(fd);

当子进程从父进程继承描述符时,此示例有效。你会想pipe 在你之前fork打电话。

于 2012-10-28T09:39:33.493 回答
2

@cnicutar 已经回答了一个问题。另一个问题是:

 char phrase[0] = "stuff this in your pipe and smoke it";

声明一个长度为 0 的数组,并且您正在存储一个更长的字符串。

将其更改为:

char phrase[] = "stuff this in your pipe and smoke it";

C 标准要求数组的大小应大于零。

从 C99,6.7.5.2 开始:

如果它们分隔了一个表达式(它指定了一个数组的大小),则该表达式应为整数类型。如果表达式是常量表达式,它的值应大于零。

于 2012-10-28T09:48:33.253 回答