C语言 确定经过的时间

cdmah0mi  于 2023-03-17  发布在  其他
关注(0)|答案(1)|浏览(126)

我正在编写一个C程序,它可以测量从命令行运行命令所需的时间。策略是派生一个子进程来执行命令,并记录开始时间的时间戳。父进程将等待子进程终止,并记录结束时间。经过的时间是结束时间和开始时间之间的差值。父进程和子进程通过共享内存进行通信。但是,我发现父进程没有收到子进程的启动时间,是不是我的共享内存出错了?
代码如下所示。

#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>

#define BUFFER_SIZE 10

typedef struct {
    time_t sec;
    suseconds_t msec;
} item;

item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;

int main()
{
pid_t pid;
    char *ls;
    scanf("%s", ls);

    /* fork a child process */
    pid = fork();

    if (pid == 0) { /* child process */
        struct timeval current;
        gettimeofday(&current, NULL);
        
        item starting_time;
        starting_time.sec = current.tv_sec;
        starting_time.msec = current.tv_usec;
        
        buffer[in] = starting_time;
        execlp(ls, "ls", NULL);
    }
    else { /* parent process */
        wait(NULL);
        
        item starting_time;
        starting_time = buffer[out];
        
        struct timeval current;
        gettimeofday(&current, NULL);
        
        long seconds = current.tv_sec - starting_time.sec;
        printf("The elapsed time is: %ld", seconds);
        
    }
}

另一件事是,我不知道如何运行一个命令,除了执行C程序在终端如下

./time ls
time.c
time

Elapsed time: 0.25422
pbpqsu0x

pbpqsu0x1#

item buffer[BUFFER_SIZE];
...
pid = fork();

这不是共享内存。Fork会创建一个新进程,它会复制所有的东西,复制的缓冲区独立于旧的缓冲区,改变不会传播。
有一些随机介绍共享内存我发现:https://www.tutorialspoint.com/inter_process_communication/inter_process_communication_shared_memory.htm
或包括叉:https://www.geeksforgeeks.org/fork-memory-shared-bw-processes-created-using/
幸运的是,您并不真的需要共享内存,只需在调用fork之前测量启动时间即可。

struct timeval starting_time;
gettimeofday(&starting_time, NULL);
pid = fork();
 
if (pid == 0) { /* child process */
    execlp(ls, "ls", NULL);
}
else { /* parent process */
    wait(NULL);
            
    struct timeval current;
    gettimeofday(&current, NULL);
    
    long seconds = current.tv_sec - starting_time.sec;
    printf("The elapsed time is: %ld", seconds);
    
}

相关问题