Monday, July 5, 2010

contoh enam

/* contoh6.c */
#include
#include
#include
#include


/* prototype fungsi */
void doparent(char[]);
void dochild1();
void dochild2();

int main()
{
int rv=0,i;
char fname[20];
pid_t pid1,pid2;


printf("Input nama file yang telah di baca : ");
scanf("%s",fname);

pid1=fork(); /* buat proses child1 */
if(pid1==-1)
{
perror("Fork gagal");
exit(EXIT_FAILURE);
}

if(pid1==0)
{
dochild1();
pid2=fork(); /* buat proses child2 */
if(pid2==-1)
{
perror("Fork gagal");
exit(1);
}
if(pid2==0)
dochild2();
else
doparent(fname);
}

}


void doparent(char *fname){
FILE *pf; /* pointer file */
char buff;//fname[15], buff;
int i=0;

printf("Input nama file yang dibaca :");
scanf("%s",fname);

/* ambil nama file yang isinya ingin dibaca*/
pf=fopen(fname,"r"); /* buka file untuk dibaca */

if(pf==NULL){
perror("PARENT: Error : \n");
exit(EXIT_FAILURE); /* exit jika buka file gagal */
}

buff=getc(pf); /* baca karakter pertama */
printf("PARENT: ISI FILE yang dibaca\n");
while(buff!=EOF){
putc(buff,stdout); /* cetak karakter */
buff=getc(pf); /* baca karakter berikutnya sampai ketemu EOF */
}

fclose(pf); /* tutup file */
}


void dochild1(){
int i;
FILE *pf=fopen("data2.txt","w");

if(pf==NULL){
printf("CHILD1: Error\n");
exit(EXIT_FAILURE);
}

for(i=1; i<=5; ++i)
fprintf(pf,"%d.Ini dari child1\n",i);

fclose(pf);
}


void dochild2(){
int i;
FILE *pf=fopen("data3.txt","w");

if(pf==NULL){
printf("CHILD2: Error \n");
exit(1);
}

for(i=5; i>=1; --i)
fprintf(pf,"%d.Ini dari child2\n",i);
fclose(pf);
}

No comments: