I got some weird output:
Read 0 bytes: P
?\?
from my code:
#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]);
}
}
I don't know where I goes wrong, any idea?
pid = fork(); pipe(fd);
This example works when child processes inherit descriptors from the parent. You'll want to call pipe
before you fork
.
@cnicutar already answered one issue. Another problem is:
char phrase[0] = "stuff this in your pipe and smoke it";
declares a 0-length array and you are storing a string which is much longer.
Change it to:
char phrase[] = "stuff this in your pipe and smoke it";
C standard mandates that size of an array should be greater than zero.
From C99, 6.7.5.2:
If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.