#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include "safe-fork.h"
#include "split.h"
char **read_lines_input(char **args);
char **read_all_input(char **args);
int main(int argc, char **argv) {
pid_t pid;
if(strcmp(argv[0], "-i") != 0) {
pid = safe_fork();
if(pid < 0) {
perror("Fork Didn't Work");
exit(-1);
}
else if(pid == 0) {
if(argv[0] != NULL) {
int a;
a = execvp(argv[0], read_all_input(argv));
if(a == -1) {
perror("Execvp failed!");
exit(-1);
}
}
else {
int a;
a = execvp("echo", read_all_input(argv));
if(a == -1) {
perror("Execvp failed!");
exit(-1);
}
}
exit(0);
}
else {
int status;
status = wait(NULL);
if(status == -1) {
perror("Child Exe Failed\n");
exit(EXIT_FAILURE);
}
else return EXIT_SUCCESS;
}
}
else {
char **temp;
temp = read_lines_input(argv);
while(temp != NULL) {
pid = safe_fork();
if(pid == 0) {
if(argv[1] != NULL)
execvp(argv[1], temp);
else execvp("echo", temp);
exit(-1);
}
else {
int status;
wait(&status);
if(status == -1) {
perror("Child Exe Failed\n");
exit(EXIT_FAILURE);
}
else return EXIT_SUCCESS;
}
temp = read_lines_input(argv);
}
}
return 0;
}
char **read_all_input(char **args) {
char **input;
char *temp;
int i = 0;
input = malloc(sizeof(char *) * 10);
temp = malloc(1000);
if(args[0] == NULL) {
input[0] = malloc(5);
strcpy(input[0], "echo");
i++;
}
else {
while(args[i] != NULL) {
input[i] = malloc(strlen(args[i]) + 1);
strcpy(input[i], args[i]);
i++;
}
}
while(fgets(temp, 1000, stdin) != NULL) {
char **split_strings;
int j = 0;
split_strings = split(temp);
while(split_strings[j] != NULL) {
input[i] = malloc(strlen(split_strings[j]) + 1);
strcpy(input[i], split_strings[j]);
i++;
j++;
}
}
i++;
input[i] = NULL;
return input;
}
char **read_lines_input(char **args) {
char **input;
char **split_strings;
char *temp;
int i = 0;
int j = 1;
input = malloc(sizeof(char *) * 100);
temp = malloc(1000);
if(args[1] == NULL) {
input[0] = malloc(5);
strcpy(input[0], "echo");
i++;
}
else {
while(args[j] != NULL) {
input[i] = malloc(strlen(args[j]) + 1);
strcpy(input[i], args[j]);
i++;
}
}
if(fgets(temp, 1000, stdin) == NULL)
return NULL;
j = 0;
split_strings = split(temp);
while(split_strings[j] != NULL) {
input[i] = malloc(strlen(split_strings[j]) + 1);
strcpy(input[i], split_strings[j]);
i++;
j++;
}
i++;
input[i] = NULL;
return input;
}
尝试使用fork时,我总是收到错误消息,说资源暂时不可用。我正在通过我所连接的大学服务器进行测试。是因为叉子炸弹?我不明白为什么会这样,如果有人可以帮助解释,我将不胜感激。我的教授向我提供了安全叉和分叉。
d
最佳答案
您可能打开了太多文件描述符。达到了服务器限制,只能由root用户更改,或者已经达到用户限制。如果是用户限制,则可以更改它。
检查系统文件描述符限制
# See system file descriptor max:
cat /proc/sys/file-max
# See number of file descriptors used:
cat /proc/sys/fs/file-nr
检查用户描述符限制
# See limit
ulimit -n
# See how much is used
lsof | wc -l
# Change limit
ulimit -Sn <number>
关于c - 使用fork()时资源暂时不可用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47523953/