C fork ve pipe kullanımı

C fork ve pipe kullanımı

Child process yaratmak için fork() sistem çağrısını kullanıyoruz. fork() sistem çağrısından return ile gelen değerin durumları;

fork()=0 child process olduğunu
fork()<0 child process oluşmamış
fork()>0 parent process de olduğunu

Pipe ise; pipe () bilgileri bir işlemden diğerine geçirmek için kullanılır. pipe () tek yönlüdür, bu nedenle, işlemler arasındaki iki yönlü iletişim için her yön için bir tane olmak üzere iki boru ayarlanabilir.

 

C fork ve pipe örnek

// by Yigit
// yigitaltunay.com
//   Pipe ve fork kullanımı | Bir tane parent iki tane child mevcut.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>

int yigit()
{

    int fd[2]; // 0-Oku, 1-Yaz
    pipe(fd);  // Pipe oluşturdum

    int pid = fork();
    int getid = getpid();

    /*  if (pipe(fd) < 0) 
    {
        exit(1);
    } */

    if (pid > 0)
    {
        int pid2 = fork();
        if (pid2 > 0)
        { //parent olsun
            printf("Parent..  \n");
        }
        else if (pid2 == 0)
        {
            

            close(fd[0]);

            char bilgi[1000];

            FILE *fp = fopen("OperatingSystemNotes.txt", "r");
            fscanf(fp, "%s", bilgi);
            printf("OperatingSystemNotes.txt =  %s  \n ", bilgi); // Okunan yazı
            write(fd[1], bilgi, strlen(bilgi) + 1);
            printf("Okuyan cocuk | Process PID =%d \n", getid);
            close(fd[1]); // yazma ile işim bitti.
        }
    }
    else if (pid == 0)
    {
       

        wait(NULL); // Okuma işleminin bitmesini bekle..

        char bilgi[1000];

        close(fd[1]); 

        read(fd[0], bilgi, 100); // Pipedan Okuma..
        printf(" Yazan cocuk  | Process PID =%d \n", getid);
        FILE *fp = fopen("OperatingSystemNotes2.txt", "a");
        fprintf(fp, "%s\n", bilgi);

        // Yazılan txt okuma
        FILE *yg = fopen("OperatingSystemNotes2.txt", "r");
        fscanf(yg, "%s", bilgi);
        printf("OperatingSystemNotes2.txt =  %s  \n ", bilgi);

        close(fd[0]); 
    }
}
int main()
{
    printf("                       \n");

    printf("#####Start####\n");
    printf("                      \n");
    yigit();
}

 

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir