后台进程(守护进程)用C不execvp()-ing [英] Background Process (Daemon) in C not execvp() -ing
问题描述
所以,我想运行它的后台进程和execvp。
当我输入CP /路径/文件/ var / tmp中,这个过程是不复制文件。
So, I am trying to run a background process and execvp from it. When i enter cp /path/file /var/tmp, the process is not copying the file.
下面是我的code,以供参考:
Here is my code for reference:
void cmd_bg(char command[])
{
pid_t process_id = 0;
pid_t sid = 0;
char* argv[512];
getArgv(command,argv);
// Create child process
process_id = fork();
// Indication of fork() failure
if (process_id < 0)
{
printf("fork failed!\n");
// Return failure in exit status
exit(1);
}
// PARENT PROCESS. Need to kill it.
if (process_id > 0)
{
printf("process_id of child process %d \n", process_id);
// return success in exit status
exit(0);
}
//unmask the file mode
umask(0);
//set new session
sid = setsid();
if(sid < 0)
{
// Return failure
exit(1);
}
// Change the current working directory to root.
chdir("/");
// Close stdin. stdout and stderr
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
execvp(argv[0],argv);
}
}
void getArgv(char command[], char* argv[512])
{
char *token;
int count = 0;
int pid = 0;
int ex = 0;
char *absPath;
char pwdtemp[512];
strcpy(pwdtemp,pwd);
token = strtok(command, " ");
while(token!=NULL)
{
argv[count++] = token;
printf("%s\n",argv[count-1]);
token = strtok(NULL," ");
}
argv[count] = '\0';
}
我真诚地希望有人能帮助我。谢谢!
I sincerely hope someone can help me. Thanks!
修改:我找到了解决办法。我不能自答案,因为我不尚未有100次。
反正这样的人士可能会认为此线程在未来的:
EDIT: I FOUND THE SOLUTION. I CANT SELF-ANSWER BECAUSE I DONT HAVE 100 REPS YET. ANYWAYS FOR PEOPLE WHO MIGHT VIEW THIS THREAD IN THE FUTURE:
确定。我想通了这个问题。
OK. I figured out the problem.
首先,我注释掉
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
chdir("/");
接下来,而不是直接调用cmd_bg,我创建了:
Next, instead of calling the cmd_bg directly, I created:
void temp1(char command[])
{
int pid = fork();
if(pid==0)
cmd_bg(command);
else
waitpid(-1, NULL, 0);
}
这似乎现在的工作!由于一吨您的输入家伙!
It seems to work now! Thanks a tonne for your input guys!
推荐答案
这是你叫你的程序任何机会, CP
?如果是这样的话,你 execvp()
将一遍又一遍拨打代替程序, /斌/ CP
。这也将有助于获得完整的code。
any chance that you called your program cp
? if this is the case you execvp()
will call the program over and over again, instead of /bin/cp
. It also would be helpful to get the complete code.
这篇关于后台进程(守护进程)用C不execvp()-ing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!