lemonade
where dream meets reality
Linux Anonymous (Unnamed) Pipe Example
Categories: C

simple.cdownload link

// unnamed pipe
// Firman Gautama

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>

int main(void) {

int p, blah[2], check;
int nilai;

// sebelum fork
check = pipe(blah);

if(check < 0)
{   printf(“pipe gagaln”);
exit(0);
}

system(“clear”);
// forking stuff
p = fork();

if(p < 0)
{
printf(“fork() gagal!n”);
}

else if(p == 0)
{
printf(“ini childn”);
printf(“Masukkan angka : “);

// get ‘nilai’
scanf(“%d”, &nilai);

//pipes blah[0] == read, blah[1] == write
write(blah[1], (int *) &nilai, sizeof(nilai));
}

else
{
read(blah[0], (int *) &nilai, sizeof(nilai));
printf(“ini parentn”);
printf(“isi nilai : [%d]n”, nilai);
wait(&p);
}
return 0;
}

———————————————————————————————————————-

advanced.cdownload link

// unnamed pipe
// Firman Gautama

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>

struct data {
char nama[128];
int umur;
};

int main(void) {

int p, blah[2], check;
struct data input;

// sebelum fork
system(“clear”);
check = pipe(blah);

if(check < 0)
{   printf(“pipe gagaln”);
exit(0);
}

// forking stuff
p = fork();

if(p < 0)
{
printf(“fork() gagal!n”);
}

else if(p == 0)
{
printf(“ini childn”);

// get ‘nilai’
printf(“Masukkan nama [max 128] : “);
// ambil semua string sampe ketemu n (new line)
scanf(“%[^n]”, input.nama);

printf(“masukan umur : “);
scanf(“%d”, &input.umur);

//pipes blah[0] == read, blah[1] == write
write(blah[1], (struct data *) &input, sizeof(struct data));
close(blah[1]);
}

else
{
read(blah[0], (struct data *) &input, sizeof(struct data));
printf(“ini parentn”);
printf(“isi nama : [%s]n”, input.nama);
printf(“isi umur : [%d]n”, input.umur);
wait(&p);
}
return 0;
}

Leave a Reply