Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h> // for pipe()
- #include <string.h>
- #include <time.h>
- //
- // unnamed pipe example
- //
- int main(int argc, char *argv[])
- {
- srand(time(NULL));
- int r = (rand() % 10)+1;
- printf("%d\n",r);
- int tomb[r];
- int i;
- for(i = 0; i < r; i++){
- tomb[i] = rand() % 10;
- }
- for(i = 0; i < r; i++){
- printf("tomb elemeke: %d\n", tomb[i]);
- }
- int pipefd[2]; // unnamed pipe file descriptor array
- int pipefd2[2]; // unnamed pipe file descriptor array
- pid_t pid;
- char sz[100]; // char array for reading from pipe
- if (pipe(pipefd) == -1 || pipe(pipefd2)) {
- perror("Hiba a pipe nyitaskor!");
- exit(EXIT_FAILURE);
- }
- pid = fork(); // creating parent-child processes
- if (pid == -1) {
- perror("Fork hiba");
- exit(EXIT_FAILURE);
- }
- if (pid == 0){ //1 az iró, 0 az olvasó? pipe = olvasó és író vége van
- // child process
- //sleep(3); // sleeping a few seconds, not necessary - nem kéne erőltetni
- //close(pipefd[1]); //Usually we close the unused write end
- printf("Gyerek elkezdi olvasni a csobol az adatokat!\n");
- int i = 0;
- while(read(pipefd[0],sz,sizeof(sz))){
- printf("Gyerek olvasta uzenet: %s\n",sz);
- //write(pipefd2[1],"Hajra vasas\n",12);
- write(pipefd2[1],*tomb[i],sizeof(tomb[i]));
- i++;
- }; // reading max 100 chars - read addig vár, ameddig nem érkezik adat -> szinkronizálás
- close(pipefd[0]); // finally we close the used read end
- close(pipefd2[1]);
- }
- else{ // szulo process
- //sleep(3);
- printf("Szulo indul!\n");
- //close(pipefd[0]); //Usually we close unused read end
- int i = 0;
- while(i < r){
- //write(pipefd[1], "Hajra Fradi!",13); //13 = tobábbítandó karakterek száma
- write(pipefd[1],*tomb[i],sizeof(tomb[i])); //13 = tobábbítandó karakterek száma
- read(pipefd2[0],sz,sizeof(sz));
- printf("Szülő olvasta uzenet: %s\n",sz);
- i++;
- }
- close(pipefd[1]); // Closing write descriptor
- close(pipefd2[0]);
- printf("Szulo beirta az adatokat a csobe!\n");
- fflush(NULL); // flushes all write buffers (not necessary)
- //wait(); // waiting for child process (not necessary)
- // try it without wait()
- printf("Szulo befejezte!\n");
- }
- exit(EXIT_SUCCESS); // force exit, not necessary
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement