leobegin2016
2017-05-07 16:58
采纳率: 100%
浏览 2.1k

多线程 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);
     }
    
    点赞 打赏 评论
  • leobegin2016 2017-05-08 09:04

    图片说明

    点赞 打赏 评论

相关推荐 更多相似问题