Я новичок в языке Си. У меня есть вопрос, и вопрос только о моем любопытстве. Я недавно выполнил задание. Следующий код вычисляет время процесса между родителем и ребенком. Я принимаю команду, как ls,pwd
и т. Д. Через ввод. Например, хотя код вычисляет время команды -ls
, он не вычисляет ls -l
. Я знаю, что мне нужно изменить execlp
, но я не знаю, какой из них лучше в соответствии с этой семьей exec? Другими словами, как я могу интегрировать настоящий тип семейства exec()
в мой код? Не могли бы вы мне помочь?
Мой пример вывода для ls
:
ls
a.out main.c
2006152 мс
Мой вывод для ls -l
:
ls -l
Ошибка exec: Нет такого файла или каталога
Мои коды:
#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");
}