1

我正在编写一个程序,它接收命令名称和参数以及可选的字符串“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 参数未通过时有效,但在通过时我尝试用“&”替换它,但它没有用,感谢各位的帮助。

4

1 回答 1

4

后台程序(或不后台程序)之间的区别在于等待它完成,或者不等待。因此,您实际上不必使用两个不同的 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.
于 2013-12-26T20:25:06.447 回答