您的位置:首页 > 运维架构 > Shell

linux c编程中调用 shell 命令

2015-07-07 14:51 791 查看
system 函数,会调用fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD 信号会被暂时搁置,SIGINT和SIGQUIT 信号则会被忽略。

/*******************************************************
本程序作为一个父进程,父进程调用子进程,然后监视子进程
的允许情况。
可以将本进程作为守护进程(具体百度)
可以把本程序添加到 /etc/rc.local 中,实现开机自启动(具体百度)
********************************************************/

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <linux/stat.h>
#include <sys/wait.h>

#include <errno.h>
#include <stdlib.h>
#include <stddef.h>
#include <nvram.h>

#include <unistd.h>

int main(void)
{
int ret;

while(1){

printf("开始启动子进程\r\n");

/*
调用 system 函数。该函数会去调用子进程,
假设子进程为 /home 目录下的 client 程序
使用 system 当调用子进程后,父进程将等待
子进程退出
*/
ret = system("/home/client");

/*
程序能运行到这里,说明子进程已经退出了
ret 为返回值,返回值为 子进程 main 函数中的
return 值。但实际并不相等,具体百度
*/
printf("子进程退出,返回值 %d\r\n", ret);

/*
对返回值做个判断,是否是正常退出,也就是 return 0
*/
if((-1 == ret) || (WEXITSTATUS(ret) != 0xa)){       //错误
printf("非正常退出子进程\r\n");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: