Linux C进程、线程

1、进程间通信:

库 <sys/types.h>

         在用户空间是不可能实现进程通信,可通过Linux内核创建对象来通信

pid_t pid;   //进程号的类型定义

pid = fork();   //创建进程

if(pid == 0){};   //子进程

if(pid == 1){};   //父进程

2、线程间通信:

库 <pthread.h>

         在用户空间可以实现线程间通信,通过全局变量通信

pthread_t tid; //线程的类型定义

int ret;

//创建线程。线程标识符、线程属性、线程函数的起始地址、传递给线程的参数

ret = pthread_create(&tid, NULL, fun, (void *)str);


进程:

  1 #include <stdio.h>
  2 #include <sys/types.h>
  3 
  4 int main()
  5 {
  6         pid_t pid;      //定义进程号类型,库 <sys/types.h>
  7         pid = fork();
  8         int process_inter = 0;  //通过全局变量也无法在用户空间实现进程通信
  9         if(pid == 0)    //子进程
 10         {
 11                 int i;
 12                 for(i = 0; i < 5; i++)
 13                 {
 14                         while(process_inter == 0);
 15                         printf("This is child process i = %d\n", i);
 16                         usleep(100);
 17                 }
 18         }
 19         if(pid > 0)     //父进程
 20         {
 21                 int i;
 22                 for(i = 0; i < 5; i++)
 23                 {
 24                         printf("This is parent process i = %d\n", i);
 25                         usleep(100);
 26                 }
 27                 process_inter = 1;
 28         }
 29         while(1);
 30         return 0;
 31 }

执行:(ctrl + c 结束运行)



线程:

注意---gcc编译时,需加-lpthread参数。

pthread不是linux下的默认的库,也就是在链接的时候,无法找到phread库中函数的入口地址,于是链接会失败。

  1 //注意:编译时 gcc -lpthread -o build thread.c
  2 /*
  3  * File: thread.c
  4  * --------------
  5  *  
  6  */
  7 
  8 #include <stdio.h>
  9 #include <pthread.h>
 10 
 11 int thread_inter = 0;   //全局变量 实现线程间通信,在用户空间
 12 void *fun(void *var)
 13 {
 14         int i;
 15         while(thread_inter == 0);       //等待。直到父线程结束,并将 thread_inter 置1
 16         for(i = 0; i < 5; i++)
 17         {
 18                 usleep(100);
 19                 printf("this is fun i = %d\n",i);
 20         }
 21 }
 22 
 23 int main()      //主线程
 24 {
 25         int i;
 26         char *str = "hello linux\n";
 27         pthread_t tid;  //定义线程
 28         int ret;
 29         ret = pthread_create(&tid, NULL, fun, (void *)str);     //创建线程。线程标识符、线程属性、线程函数的起始地址、传递给线程的参>
    数  
 30         if(ret < 0)
 31         {   
 32                 printf("create thread failure\n");
 33                 return -1;
 34         } 
 35         for(i = 0; i < 5; i++)
 36         {   
 37                 usleep(100);
 38                 printf("this is main fun i = %d\n",i);
 39         }
 40         thread_inter = 1;       //将 thread_inter 置1,子进程开始执行
 41         while(1);
 42         return 0;
 43 }


执行:

参数 -lpthread (指定链接 pthread 库)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值