这个程序应该使用fork()来创建进程,将子进程的PID存入一个单链表,fork失败后一次杀掉一个进程,然后释放链表中的节点,最后打印出多少个进程是在结束程序之前创建的。
目前它不做这些事情,我不知道该去哪里。它会正确编译,但是当我在必须使用的 Minix 终端中运行它时,它什么也没做。当我关闭终端时,我最终得到“关闭:不能 fork():资源暂时不可用”。所以出了点问题,我们将不胜感激。谢谢你。
/*
Problem: Write a complete C-program to determine the number of
simultaneous processes Minix can support for a single user. Be
aware that a users' login shell is itself a process. Once this has
been determined, any processes created will have to be terminated.
Created processes will have to be kept track of in a singly linked list
with node structure dynamically allocated at runtime.
Solution: Create processes until fork() fails. Each child process will
call pause(). The signal will be delivered by the parent process using
kill() system call. When fork() fails, terminate the children processes
one at a time using childs' PID and SIGKILL signal. You will have to
keep track of children process PIDs in a singly linked list.
Data-structure used: A singly linked list
Accessing functions for the data structure: malloc() and free() to
dynamically handle the node storage
Errors handled: None.
Limitations: None.
*/
#define _POSIX_SOURCE
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct lnode {
int pid;
struct lnode *next;
};
/* Dynamically allocates node storage at runtime using
malloc().
*/
struct lnode*
getnode(void)
{
return malloc(sizeof(struct lnode));
}
/* Frees nodes dynamically allocated by getnode before
the program is terminated.
*/
void
freenode(struct lnode *tmp)
{
free(tmp);
}
/* Display the output of how many simultaneous processes Minix
can support for a single user.
*/
void
printtotal(int count)
{
fprintf(stdout, "For this user: %d\n", count);
}
int
main(int argc, char *argv[])
{
struct lnode *curr;
struct lnode *tmp;
int count = 1;
int pidholder = 1;
tmp = NULL;
while(pidholder > 0) {
curr = getnode();
pidholder = fork();
if(pidholder < 0)
exit(-1);
else if(pidholder == 0)
pause();
else if(pidholder > 0) {
curr->pid = pidholder;
curr->next = tmp;
tmp = curr;
}
}
curr = tmp;
while(curr) {
pidholder = curr->pid;
kill(pidholder, SIGKILL);
tmp = curr;
curr = curr->next;
freenode(tmp);
}
printtotal(count);
exit(0);
}