Created
July 3, 2011 06:44
-
-
Save alecbz/1062011 to your computer and use it in GitHub Desktop.
forking and piping in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
int main() | |
{ | |
pid_t pid = fork(); | |
if(pid == -1) | |
fprintf(stderr,"There was an error\n"); | |
else if(pid == 0) | |
printf("I am the child. I do not know my pid.\n"); | |
else | |
printf("I am the parent. The child's pid is %d.\n",pid); | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
int main() | |
{ | |
int pip[2]; | |
if(pipe(pip) == -1) | |
{ | |
fprintf(stderr,"There was an error establishing the pipe.\n"); | |
return 1; | |
} | |
pid_t pid = fork(); | |
if(pid == -1) | |
{ | |
fprintf(stderr,"There was an error forking.\n"); | |
return 1; | |
} | |
char buffer[80]; | |
if(pid == 0) | |
{ | |
char* msg = "This is a message from the child: Hello!"; | |
write(pip[1],msg,strlen(msg)+1); | |
} | |
else | |
{ | |
read(pip[0],buffer,sizeof(buffer)); | |
printf("The parent received this string from the child: \"%s\"\n",buffer); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment