Home > Net >  how to you use execvp() one by one
how to you use execvp() one by one

Time:09-23

I want to use execvp twice 1 by 1 for 2 commands, the new program I want to awake is hcp with a couple of parameters and I am using this like that

int pid = 0;
char* spec_command[] = {"/usr/bin/hcp", "--enable-product","Performance", NULL};
char* spec_command2[] = {"/usr/bin/hcp", "--enable-product","Threat Prevention", NULL};
pid = fork();
if (pid == 0) 
{
    execvp("/usr/bin/hcp", spec_command);
    execvp("/usr/bin/hcp", spec_command2);
}

but just one of them is executed? how can I cause both of them work? thanks

CodePudding user response:

You need to fork() twice since execvp replaces the current process completely and never returns (unless it fails).

Example:

#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

void run(const char* file, char* argv[]) {
    pid_t pid = fork();
    if (pid == 0)
    {
        execvp(file, argv);
        exit(1);
    }
}

int main(void) {
    char* spec_command[] = {"/usr/bin/hcp", "--enable-product","Performance", NULL};
    char* spec_command2[] = {"/usr/bin/hcp", "--enable-product","Threat Prevention", NULL};
    run("/usr/bin/hcp", spec_command);
    run("/usr/bin/hcp", spec_command2);

    int wstatus;
    while(wait(&wstatus) != -1) {}
}

This runs both commands in parallel. If you want to wait for the first one to finish before starting the second one, put a wait after the first run too - or in the the run function. If you want to continue the program without waiting for the processes to finish, skip the wait.

CodePudding user response:

didnt work :( my code

const char* spec_command[] = {"/usr/bin/hcp", "--enable-product","Performance", NULL};
const char* spec_command2[] = {"/usr/bin/hcp", "--enable-product","Threat Prevention", NULL}; 
disableThreatPrevention(spec_command); 
disableThreatPrevention(spec_command2);


void disableThreatPrevention(const char* spec_command[]) { 

int pid = 0 ;
 pid = fork(); 
if (pid == 0) 
{ 
   execvp("/usr/bin/hcp", spec_command) 
   exit(1);
}
}
  • Related