【发布时间】:2020-07-07 00:17:29
【问题描述】:
我的作业是从 Linux shell 执行一个带有 N 个参数的 C 程序:N 个文件名。
我必须创建 N 个进程,并且为每个进程创建一个 .bak 文件,文件名在参数中指定。
教授建议我们使用cp 命令,但我不知道如何进行。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <limits.h>
typedef char stringa[80];
typedef stringa strvett[DIM];
void usage(char* prog_name) {
fprintf(stderr,"Usage:\n\t%s: file1 file2 ... fileN dir_dest.\n", prog_name);
}
void main(int argc, char *argv[]) {
int i = 0, j = 0, status, N = argc - 2, n_children = N;
int[N] pid;
char[N]* files;
char[PATH_MAX - 1] wd;
char term = '0';
if (strcmp(argv[argc - 1], getcwd(wd, sizeof(wd)))) {
fprintf(stderr, "Invalid directory.\n");
usage(argv[0]);
exit(EXIT_FAILURE);
}
for (i = 0; i < N; i++) {
char[strlen(argv[i + 1])] files[i];
strcpy(files[i], argv[i + 1]);
}
for (j = 0; j < n_children; j++ ) {
pid[j] = fork();
if (pid[j] == 0) { // Executed by child
if (term == '1') exit(0);
else {
term = '1';
execl("/bin/ls", "ls", "-l", (char*)0);
// cp command???
}
}
else {
if (pid[j] > 0) printf("%d: child created with PID %d\n", getpid(), pid[j]); // Executed by parent
else {
perror("Fork error");
exit(1);
}
}
}
}
【问题讨论】:
-
当你在子进程 pid==0 时,你应该在那里创建文件
-
@Singh 好的,我该怎么做?我在网上浏览了一些文章,我找不到任何明确的内容
-
这可能看起来像个傻瓜,但它(IMO)非常重要。不要打印使用说明和错误消息。用法语句NOT 是错误,并且将用法与错误一起打印会掩盖错误。 wrp.github.io/blog/2020/02/21/succinct-err-messages.html