leobegin2016 2017-05-07 16:58 采纳率: 100%
浏览 2171
已采纳

多线程 linux下gcc编译一直通不过

#include
2 #include
3 #include
4 #include
5
6 void print(pid_t);
7
8 sem_t *sem;
9 int val;
10 int main(int argc,char *argv[])
11 {
12 int n = 0;
13 if(argc != 2);
14 {
15 printf("please input afile name!\n");
16 exit(1);
17 }
18 sem = sem_open(argv[1],O_CREAT,0644,2);
19
20 while(n++<5)
21 {
22 if(fork()==0)
23 {
24 sem_wait(sem);
25 print(getpid());
26 sleep(1);
27 sem_post(sem);
28 printf("I'm finished,my pid is %d\n",getpid());
29 return 0;
30 }
31 }
32
33 wait();
34 sem_close(sem);
35 sem_unlink(argv[1]);
36 exit(0);
37 }
38
39 void print(pid_t pid)
40 {
41 printf("I get it,my pid is %d\n",pid);
42 sem_getvalue(sem,&val);
43 printf("Now the value have %d\n",val);
44 }

  • 写回答

2条回答 默认 最新

  • 普通网友 2017-05-08 00:01
    关注

    try compile this with

    gcc sem.c -o sem -lrt

     #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <semaphore.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
    
    void print(pid_t);
    
    sem_t *sem;
    int val;
     int main(int argc,char *argv[])
     {
     int n = 0;
     if(argc != 2);
     {
     printf("please input afile name!\n");
     exit(1);
     }
     sem = sem_open(argv[1],O_CREAT,0644,2);
    
     while(n++<5)
     {
     if(fork()==0)
     {
     sem_wait(sem);
     print(getpid());
     sleep(1);
     sem_post(sem);
     printf("I'm finished,my pid is %d\n",getpid());
     return 0;
     }
     }
    
     wait();
     sem_close(sem);
     sem_unlink(argv[1]);
     exit(0);
     }
    
     void print(pid_t pid)
     {
     printf("I get it,my pid is %d\n",pid);
     sem_getvalue(sem,&val);
     printf("Now the value have %d\n",val);
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码