C 中的 Exec 系列用法

Exec Family Usage in C

我是C语言初学者。我有一个问题,这个问题只是关于我的好奇心。我最近做了一个任务。下面的代码计算父子之间的进程时间。我在指挥 像 ls,pwd 等通过输入。作为示例,虽然代码计算 -ls 命令的时间,但它不计算 ls -l。我知道我需要更改 execlp 但我不知道根据该 exec 家族哪个更好?换句话说,如何将真正的 exec() 系列类型集成到我的代码中?你能帮帮我吗?

我的 ls 示例输出:

ls
a.out main.c
2006152 ms

我对 ls -l 的输出:

ls -l
Error exec: No such file or directory

我的代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>

#define N 20

void ChildProcess();    
void ParentProcess();    

struct timeval start, end;
char *input;
int main (int argc,char **argv) {
    input = argv[1];
    pid_t pid;
    pid = fork();
    if (pid == 0){
        ChildProcess ();
    }
    else {
        wait (NULL);
        ParentProcess ();
    }

    return 0;
}

void ChildProcess () {
    /* the size (in bytes) of shared memory object */
    const int SIZE = 4096;
    /* name of the shared memory object */
    const char* name = "OS";
    /* shared memory file descriptor */
    int shm_fd;
    /* pointer to shared memory obect */
    long int* ptr;
    /* create the shared memory object */
    shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
    /* configure the size of the shared memory object */
    ftruncate(shm_fd, SIZE);
    /* memory map the shared memory object */
    ptr =(long int*)mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
    gettimeofday(&start, NULL);
    printf("%ld ",start.tv_usec);
    *ptr=start.tv_usec;
    if (execlp (input, "", (char *) 0) < 0)
    {
        perror ("Error exec");
        exit (0);}
    }
}

void ParentProcess () {
    /* the size (in bytes) of shared memory object */
    const int SIZE = 4096;
    /* name of the shared memory object */
    const char* name = "OS";
    /* shared memory file descriptor */
    int shm_fd;
    /* pointer to shared memory object */
    long int* ptr;
    /* open the shared memory object */
    shm_fd = shm_open(name, O_RDONLY, 0666);
    /* memory map the shared memory object */
    ptr =(long int*)mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
    /* read from the shared memory object */
    printf("%ld usec okunan\n ", *ptr);
    long int start_usec = *ptr;
    /* remove the shared memory object */
    shm_unlink(name);
    gettimeofday(&end,NULL);
    printf("%ld son : ",end.tv_usec);
    printf ("Total time : %ld %s dir \n", end.tv_usec-start_usec, "ms");
}

您负责编写代码将输入字符串拆分为单独的参数,您可以将这些参数传递给 execvp:

/* Take your string "ls -l" and split it up into an array like this: */
char* split[3];
split[0] = "ls";
split[1] = "-l";
split[2] = NULL;
execvp(split[0], split);

如果您不知道如何在 C 中拆分字符串来实现这一点,您将不得不单独研究和学习。

或者,您可以请 shell 为您完成。但是,这也会测量 shell:

的启动和处理时间
char* command = "ls -l";
execlp("sh", "sh", "-c", command, NULL);