Skip to content

Instantly share code, notes, and snippets.

@alecbz
Created July 3, 2011 06:44
Show Gist options
  • Save alecbz/1062011 to your computer and use it in GitHub Desktop.
Save alecbz/1062011 to your computer and use it in GitHub Desktop.
forking and piping in C
#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;
}
#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