【问题标题】:run a program in background with execvp system call in c在c中使用execvp系统调用在后台运行程序
【发布时间】:2014-01-14 11:01:49
【问题描述】:

我正在编写一个程序,它接收命令名称和参数以及可选的字符串“bg”,如果传递了“bg”字符串,我的程序应该在后台执行命令及其参数,如果不是在前台,这是我的代码:

#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 参数未通过时有效,但在通过时我尝试用“&”替换它,但它不起作用,感谢各位帮助。

【问题讨论】:

  • 你明白“在后台运行程序”是什么意思吗?
  • &amp; 不是由execvp() 处理的,而是由shell 处理的,类似于处理bg 令牌的方式。由于你没有使用 shell 来运行命令,所以它不会有任何效果。
  • 如果你想在后台运行,直接退出,不要调用wait()
  • @Ignacio Vazquez-Abrams 是的,我想是的,这是一个家庭作业。

标签: linux system posix system-calls execvp


【解决方案1】:

后台程序(或不后台程序)的区别在于等待它完成,或者不等待。因此,您实际上不必使用两个不同的 execvp。但是,您需要从参数中删除尾随的 bg。附加 & 不会做任何事情 - & 是 shell 的元字符,它告诉 shell 不要等待正在执行的程序。

所以,你应该做的是:

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.

【讨论】:

    猜你喜欢
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多