Skip to content

Instantly share code, notes, and snippets.

@xcv58
Last active August 29, 2015 13:55
Show Gist options
  • Save xcv58/8773106 to your computer and use it in GitHub Desktop.
Save xcv58/8773106 to your computer and use it in GitHub Desktop.
temp
/*
* Test fork(), pipe(), etc.
* Author: xcv58
* Date: 2/2/2014
*/
#ifndef _STDIO_H_
#define _STDIO_H_
#include <stdio.h>
#endif
#ifndef PIPE
#define PIPE 1
#endif
/* #include <stdio.h> */
/* void read() */
/* { */
/* printf("This is read.\n"); */
/* close(filedes[0]); */
/* return; */
/* } */
/* void write() */
/* { */
/* printf("This is write.\n"); */
/* close(filedes[1]); */
/* return; */
/* } */
int getLine(char* str)
{
int i = 0;
while ((str[i++] = getchar()) != '\n');
str[i] = '\0';
return 0;
}
int main()
{
printf("\n");
#ifdef PIPE
printf("%s\n",__FILE__);
char str[24];
int filedes[2];
int returnCodePipe = pipe(filedes);
if (!returnCodePipe) {
printf("Successfully create pipe.\n");
}
char readbuffer[80];
int nbytes;
#endif
int myPid = getpid();
int returnCodeFork = fork();
printf("My pid is %d\n", getpid());
if (returnCodeFork == 0) {
printf("I am child.\nMy parent pid is: %d\n", myPid);
#ifdef PIPE
if (!returnCodePipe) {
/* read(); */
/* close(filedes[1]); */
nbytes = read(filedes[0], readbuffer, sizeof(readbuffer));
printf("Received str: %s", readbuffer);
}
#endif
printf("\n");
} else {
printf("I am parent.\nMy child's pid is: %d\n", returnCodeFork);
#ifdef PIPE
if (!returnCodePipe) {
/* write(); */
/* cloese(filedes[0]); */
/* str[0] = getchar(); */
/* str[1] = '\0'; */
getLine(str);
printf("str length: %d\n", strlen(str));
write(filedes[1], str, (strlen(str)+1));
}
#endif
printf("\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment