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?
This example works when child processes inherit descriptors from the parent. You’ll want to call
pipebefore youfork.