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

多线程 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条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵