进程和线程(一)

 

1.内核分配进程ID是以严格的线性函数方式进行的。如果17是当前id的最高值,那么18就是分配给新进程的值,即使当前新进程运行时,上一个pid为17的进程已经不再运行了。直到内核分配的pid值达到了/proc/sys/kernel/pid_max,内核是不会重用以前分配的值

2.获得进程ID和父进程ID

  getpid():用于返回调用进程的ID

  getppid():用于返回调用进程的父进程的ID

  #include<stdio.h>
  #include<sys/types.h>
  #include<unistd.h>
  int main()
  {

        printf("my pid=%d\n",getpid());
        printf("father's pid=%d\n",getppid());
        return 0;
   }

  执行结果:

  [root@localhost ~]# ./pid
  my pid=9190
  father's pid=3299
3.fork():创建一个和当前进程映像一样的进程。

  fork之后是父进程先执行还是子进程先执行,这取决于cpu调度算法。

4.linux系统下的多进程遵循POSIX线程接口,称为pthread,在linux多线程需要使用的头文件为<pthread.h>。连接时需要使用库为libthread.

   void thread(void)
   {
        int i;
        for(i=0;i<3;i++)
        {
                printf("This is a pthread.\n");
                sleep(1);
        }
   }
   int main(void)
   {
        pthread_t id;
        int i,ret;
        ret=pthread_create(&id,NULL,(void*)thread,NULL);
        if(ret!=0)
        {
                printf("Create pthread error!\n");
                exit(1);
        }
        for(i=0;i<3;i++)
        {
                sleep(1);
                printf("This is the main process.\n");

        }
        pthread_join(id,NULL);
        return 0;
    }
   编译源文件:

   [root@localhost thread]# gcc pthread_test.c -o pthread_test -lpthread

   [root@localhost thread]#

  执行结果:

  [root@localhost thread]# ./pthread_test
  This is a pthread.
  This is a pthread.
  This is a pthread.
  This is the main process.
  This is the main process.
  This is the main process.
  [root@localhost thread]#

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值