Compile error on linux (a simple demo code on concept of pipe)

103 views Asked by At

So I get this error when I try to compile this code named pipe on linux

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):}

This is my code:

#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);}
}
}

How do I fix this? and the thing confuse me is what does sleep(1) means? does it mean 1 is correct and if its 1 it will go to sleep process?

3

There are 3 answers

0
Tanzer On

It seems a simple syntax error. You declared "char AMsg " and later try to refer to variable as Amsg. You simply have to change m to M .

0
Olivier Pirson On

It's a simple typo. Change AMsg by Amsg in

char *AMsg = "nodeA";

sleep suspend execution for an interval of time. See http://pubs.opengroup.org/onlinepubs/009695399/functions/sleep.html

0
resultsway On

well, you have a typo for AMsg.

sleep suspends execution of child process. They are doing that to demonstrate child process is executed after parent, or else everytime you rerun the program the results will be different.

Just remove that sleep and run the program like 10 times, the print/output sequence will be different sometimes.