在linux上编译错误(关于管道概念的简单演示代码)

时间:2015-06-14 22:50:21

标签: linux compiler-errors pipe output sleep

所以当我尝试在linux上编译这个名为pipe的代码时,我得到了这个错误

pipe.c: In function ‘main’:
pipe.c:27:14: error: ‘Amsg’ undeclared (first use in this function)
 write(fd[1], Amsg, strlen (Amsg));
              ^
pipe.c:27:14: note: each undeclared identifier is reported only once for each function it appears in
pipe.c:30:41: error: expected ‘;’ before ‘:’ token
 printf("A got: %s and i = %d\n", buf, i):}

这是我的代码:

#define SIZE 1000
#include <stdio.h>
#include <string.h>


int main(void) {

int fd[2];
char buf[SIZE];

char *AMsg = "nodeA";
char *Bmsg = "nodeB";
int i = SIZE;
pipe(fd);


if( fork() == 0) {
sleep(1);
read(fd[0], buf, 100);
i++;
printf("B got: %s and i = %d\n", buf, i);
write(fd[1], Bmsg, strlen(Bmsg));
// sleep(10);
}

else {
write(fd[1], Amsg, strlen (Amsg));
wait(NULL);
while((i = read(fd[0], buf, 100)) != 0) {
printf("A got: %s and i = %d\n", buf, i);}
}
}

我该如何解决这个问题?而让我迷惑的是睡眠(1)意味着什么?它是否意味着1是正确的,如果它是1它将进入睡眠过程?

3 个答案:

答案 0 :(得分:0)

这似乎是一个简单的语法错误。 你宣布“char AMsg” 然后尝试将变量称为Amsg。 您只需将m更改为M.

答案 1 :(得分:0)

这是一个简单的错字。 通过Amsg改变AMsg

char *AMsg = "nodeA";

睡眠暂停执行一段时间。 看到 http://pubs.opengroup.org/onlinepubs/009695399/functions/sleep.html

答案 2 :(得分:0)

好吧,你有一个错误的AMsg。

sleep暂停执行子进程。他们这样做是为了证明子进程是在父进程之后执行的,否则每次重新运行程序时结果都会不同。

只需删除该睡眠并运行程序10次,打印/输出顺序有时会有所不同。