如何在C中同时执行两个命令

时间:2019-11-24 14:01:00

标签: c

谢谢大家的建议和建议的答案,我终于自己解决了,这就是它的外观:

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

    int i;
    for (i = 1; i < argc; i++) {
        if (strcmp(argv[i], "+") == 0) {
            break;
        }
    }

    argv[i] = NULL;

    if (fork() == 0) {
        execvp(argv[1], &argv[1]);
        exit(0);
    }

    if (fork() == 0) {
        execvp(argv[i+1], &argv[i+1]);
        exit(0);
    }

    wait(NULL);
    wait(NULL);

    exit(0);

}

2 个答案:

答案 0 :(得分:1)

以OP代码为基础

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

    int i =1 ;

    // Argument list for first call
    i1 = i ;
    char *prog1[argc];
    while (strcmp(argv[i], "+") != 0) {
            prog1[i-i1] = argv[i];
            i++;
    }
    prog[i-1] = NULL ;

    // Argument list for second call
    int i2 = i ;
    char *prog2[argc];
    whlie ( i < argc ) {
        prog2[i-i2] = argv[i] ;
    } ;
    prog2[i-i2] = NULL ;

    pid_t pid1 = fork() ;
    if ( pid1 == 0) {
        execvp(prog1[0], prog1);
        exit(0);
    }

    pid_t pid2 = fork() ;
    if ( pid2 == 0) {
        execvp(prog2[0], prog2);
        exit(0);
    }

    // Wait for all childs
    int status ;
    while ( wait(&status) ) { } ;

    exit(0);
}

答案 1 :(得分:0)

派生在并行执行中工作正常,但我建议改用线程。使用更高级别的线程API或使用POSIX标准pthreads。编译时,请确保与-lpthread链接。

类似的东西:

#include <pthread.h>

typedef struct
{
  const char* command;
} thread_arg;

void* command_thread(void* v_arg)
{
  thread_arg* arg = (thread_arg*) v_arg;
  system(arg->command);
}

int main(int argc, char** argv)
{
  pthread_t thread0, thread1;
  thread_arg arg0, arg1;

  /* specify arguments */
  arg0.command = [command to execute on thread 0];
  arg1.command = [command to execute on thread 1];

  /* create threads */
  pthread_create(&thread0, NULL, command_thread, &arg0);
  pthread_create(&thread1, NULL, command_thread, &arg1);

  /* wait for threads to complete */
  pthread_join(thread0, NULL);
  pthread_join(thread1, NULL);

  return 0;
}

如果参数正确定界,将可以工作。

如果您不必使用+来分隔两个参数,则在调用该程序时,只需使用双引号,然后将argv[1]argv[2]作为命令即可。

如果这是一个赋值,并且必须使用+来定界,那么应该检查+是否在参数列表中。

int p = 0;
unsigned int i = 0;

/* check if any argument is '+' */
for(unsigned int j = 1; j < argc; j++) {
  if(strcmp(argv[j], "+") == 0) {
    p = 1;
    i = j;
  }
}

/* feel free to resize as needed */
char command0[256];
char command1[256];

if(p) {
  /* plus found, separate strings */

  /* get string before plus */
  for(unsigned int j = 1; j < i; j++) {
    strcat(command0, argv[j]);
    strcat(command0, " ");
  }

  /* get string after plus, i + 1 as i is zero based */
  for(unsigned int j = i + 1; j < argc; j++)
  {
    strcat(command1, argv[j]);
    strcat(command1, " ");
  }
}

strcat只是将第二个字符串参数复制到第一个字符串的末尾,同时还要确保命令正确地以零结尾。

相关问题