linux c编程中调用 shell 命令

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");
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值