2016-09-16 46 views
1

我有一個函數,打印一個字符在循環中的字符。我想要做的是同步父母和子女的過程,以便每個人打印一行而不會有其他干擾。我試圖用信號量來做到這一點。與系統-v信號量的父 - 子同步

這是我的代碼:

int main() { 
    int i, sem; 
    struct sembuf u = {0, 1, 0}; 
    struct sembuf d = {0 -1, 0}; 
    sem = semget(IPC_PRIVATE, 1, 0600); 
    semctl(sem, 0, SETVAL, 1); 

    if (!fork()) { 
     for (i=0;i<10;i++){ 
      semop(sem, &d, 1)) < 0) 
      print_char_by_char("hello\n"); 
      semop(sem, &u, 1); 
     } 



    } else { 
     for (i=0;i<10;i++){ 
      semop(sem, &d, 1); 
      print_char_by_char("world\n"); 
      semop(sem, &u, 1); 
     } 


     semctl(sem, 0, IPC_RMID); 
    } 
    return 0; 
} 

所以這是行不通的,印刷品都是亂碼,我真的不知道爲什麼。另外,如果我把支票semop這樣的:

if((x = semop(sem, &down, 1)) < 0) 
    perror("semop"); 

我得到semop: File too large

回答

0

根據man semop

EFBIG:對於一些操作sem_num的值小於0或 重新等於或等於集合中信號量的數量。

然後,不知道如何爲你的print_char_by_char功能,我們無法知道爲什麼你打印亂碼(記住,printf和其他被緩衝,所以你應該使用fflush下一個,或直接使用write代替。

順便說一句,我試着執行您的代碼(下面我寫的),我沒有任何問題(因爲你沒有指定你所期望的輸出),如果我刪除

semctl(sem, 0, IPC_RMID); 

也許你錯了(應該g Ø只是return之前,否則誰首先完成了一會代替去除信號集,我猜)

CODE

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/ipc.h> 
#include <sys/types.h> 
#include <sys/sem.h> 

void error_handler(const char *msg) 
{ 
    perror(msg); 
    exit(EXIT_FAILURE); 
} 

int main(int argc, const char **argv) 
{ 
    if (argc != 1) 
    { 
     fprintf(stderr, "Usage: %s <no arguments>\n", argv[0]); 
     return EXIT_FAILURE; 
    } 

    int i, sem; 
    struct sembuf u = {0, 1, 0}; 
    struct sembuf d = {0, -1, 0}; 
    sem = semget(IPC_PRIVATE, 1, 0600); 
    semctl(sem, 0, SETVAL, 1); 

    if (!fork()) 
    { 
     for (i = 0; i < 10; i++) 
     { 
      if (semop(sem, &d, 1) == -1) 
       error_handler("main | semop [d - father]\n"); 
      if (write(STDOUT_FILENO, "hello\n", 7) == -1) 
       error_handler("main | write [hello]\n"); 
      if (semop(sem, &u, 1) == -1) 
       error_handler("main | semop [u - father]\n"); 
     } 
    } else { 
     for (i = 0; i < 10; i++) 
     { 
      if (semop(sem, &d, 1) == -1) 
       error_handler("main | semop [d - child]\n"); 
      if (write(STDOUT_FILENO, "world\n", 7) == -1) 
       error_handler("main | write [world]\n"); 
      if (semop(sem, &u, 1) == -1) 
       error_handler("main | semop [u - child]\n"); 
     } 

     // semctl(sem, 0, IPC_RMID); 
    } 

    return EXIT_SUCCESS; 
} 

輸出

world 
world 
world 
world 
world 
world 
world 
world 
world 
world 
hello 
hello 
hello 
hello 
hello 
hello 
hello 
hello 
hello 
hello 

,如果你想在父子關係中同步兩個進程(這聽起來很奇怪......)我會建議你共享內存和POSIX信號量