Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7553790
  • 博文数量: 961
  • 博客积分: 15795
  • 博客等级: 上将
  • 技术积分: 16612
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-07 14:23
文章分类

全部博文(961)

文章存档

2016年(1)

2015年(61)

2014年(41)

2013年(51)

2012年(235)

2011年(391)

2010年(181)

分类: LINUX

2011-06-13 21:59:00

  1. /*
  2.  *    system函数通过调用shell程序/bin/sh来在新的进程中执行参数所指定的命令
  3.  *    Lzy 2011-6-13
  4.  */

  5. #include <stdio.h>
  6. #include <stdlib.h>

  7. int main(void)
  8. {
  9.     if(system("ls -l") != 0)        //创建新的进程
  10.     {
  11.         perror("system");
  12.         exit(0);
  13.     }
  14.     return 0;
  15. }
  1. /*
  2.  *    执行外部程序
  3.  */

  4. #include <stdio.h>
  5. #include <stdlib.h>

  6. int main(void)
  7. {
  8.     char buf[1024];
  9.     FILE *pp;
  10.     char *cmd = "ls -l";    
  11.     
  12.     //参数为可执行文件的全路径和执行参数。
  13.     //只能为读或写
  14.     if((pp = popen(cmd,"r")) == NULL)        /* 将命令的输出通过管道读取到pp之中 */
  15.     {
  16.         perror("popen");
  17.         exit(0);
  18.     }
  19.     
  20.     while(fgets(buf,sizeof(buf),pp))    /* 将pp中的数据流读取到缓冲区中 */
  21.     {
  22.         printf("%s",buf);
  23.     }
  24.     
  25.     pclose(pp);                            //等待新进程结束
  26.     return 0;
  27. }
  1. /*
  2.  *    _exit退出
  3.  */
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. int main()
  8. {
  9.   printf("Hello World.\n");
  10.   printf("ABC");
  11.   _exit(0);
  12. }
  1. /*
  2.  *    exit退出
  3.  */
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. int main()
  7. {
  8.   printf("Hello World.\n");
  9.   printf("ABC");
  10.   exit(0);
  11. }
  1. /*
  2.  *    获取进程信息
  3.  */
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <sys/wait.h>
  8. int main()
  9. {
  10.   pid_t pid;
  11.   int status;
  12.   pid = fork();                        /* 创建新的进程 */
  13.   if(pid<0)                            /* 如果进程创建失败,输出错误信息并退出 */
  14.   {
  15.     printf("fork error.\n");
  16.     exit(1);
  17.   }
  18.   if(pid==0)                         /* 子进程 */
  19.   {
  20.     printf("Child Process:\n");
  21.     printf("pid = %d\n", getpid());        /* 获取当前进程的标识符 */
  22.     printf("ppid = %d\n", getppid());        /* 获取父进程的标识符 */
  23.     printf("gid = %d\n", getpgrp());        /* 获取进程的组标识符 */
  24.     exit(1);
  25.   }
  26.   else                            /* 父进程 */
  27.   {
  28.     printf("Parent Process:\n");
  29.     printf("pid = %d\n", getpid());        /* 获取当前进程的标识符 */
  30.     printf("ppid = %d\n", getppid());        /* 获取父进程的标识符 */
  31.     printf("gid = %d\n", getpgrp());        /* 获取进程的组标识符 */
  32.     if(pid != wait(&status))             /* 等待进程结束 */
  33.     {
  34.       printf("wait error.\n");
  35.       exit(1);
  36.     }
  37.   }
  38.   return 0;
  39. }
阅读(1421) | 评论(0) | 转发(2) |
0

上一篇:execl函数

下一篇:守护进程

给主人留下些什么吧!~~