在C中使用execvp系统调用在后台运行程序 [英] run a program in background with execvp system call in c

查看:419
本文介绍了在C中使用execvp系统调用在后台运行程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序将接收命​​令名称和参数,并可选地在末尾接收字符串"bg",如果传递了"bg"字符串,则我的程序应在后台使用命令的参数来执行命令(如果不在前台) ,这是我的代码:

i'm writing a program that recieves a command name and arguments and optionally the string "bg" at the end , if the "bg" string is passed my program should execute the command with its arguments in background if not in foreground, here's my code:

#include<sys/types.h>   
#include<sys/wait.h>    
#include<unistd.h>
#include<stdio.h>
#include<errno.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char* argv[])
{

pid_t pid;
int state;

if( (pid=fork())<0) {
    perror("\nError in fork");
    exit(-1);
} 
else if(pid==0) {  
    if(strcmp(argv[argc-1], "bg") == 0 ){
        strcpy(argv[argc-1],"&");
        if( (execvp(argv[1], argv)<0)) {
            perror("\nError in first execvp");
            exit(-1);
        }
    }
    else{
        if( (execvp(argv[1], argv+1)<0)) {
            perror("\nError en second el execvp");
            exit(-1);
        }
    }   

}    
wait(&state);
printf("\nMy child %d terminated with state %d\n",pid,state);

exit(0);

}

输入示例:

./myprogram ls -lai bg   // in this case my program should execute "ls -lai" in background
./myprogram ls -lai      // in this case it should execute command normally in foreground 

当未传递bg参数时,我的代码有效,但是当传递参数时,我尝试将其替换为&".但这没有用,谢谢大家.

my code works when the bg argument is not passed but when passed i tried to substitute it with "&" but it didn't work, help is appreciated guys.

推荐答案

后台程序(或不后台)之间的区别在于等待程序完成或不等待.因此,您实际上不必使用两个不同的execvp.但是,您需要从参数中删除结尾的bg.附加&什么也不会做-&是外壳程序的元字符,它告诉外壳程序不要等待正在执行的程序.

The difference between backgrounding a program - or not - lies in waiting for it to finish, or don't wait. So you don't really have to use two different execvp's. But, you need to remove the trailing bg from the arguments. Appending the & won't do anything - the & is a metacharacter for the shell, which tells the shell not to wait for the program that's being executed.

因此,您应该做的是:

if the last argument is "bg" : decrease argc by one, set the argument that had the bg to null
fork and execvp what's in argv
if the last argument was "bg", do NOT call wait(); else call wait.

这篇关于在C中使用execvp系统调用在后台运行程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆