这个程序应该使用fork()来创建进程,将子进程的PID存储到一个单链表中,在fork失败后,一次杀死一个进程,然后释放链表中的节点,最后打印出在结束程序之前创建了多少个进程。
目前它不做这些事情,我不知道该怎么做。它将正确编译,但当我在Minix终端中运行它时,我必须使用它,它不起任何作用。当我关闭终端时,我得到的结果是" shutdown : can't fork():Resource temporarily unavailable“。因此,有些地方出了问题,任何帮助都将不胜感激。谢谢。
/*
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);
}发布于 2014-09-26 21:35:17
在把程序放在一边过夜,并在早上重新尝试之后,我发现了哪里出了问题。
当fork()在while循环中失败时,它将退出程序,这会导致问题,因为一旦我删除了这一部分,程序就会正常执行。我相信这是因为程序的kill部分没有运行,所有这些进程都在运行。此外,我意识到我忘记包括一行代码来递增计数器,以跟踪正在创建的进程数。
以下是main的工作代码:
int
main(int argc, char *argv[])
{
struct lnode *curr;
struct lnode *tmp;
int count = 1;
int pidholder = 0;
tmp = NULL;
while(pidholder >= 0) {
curr = getnode();
pidholder = fork();
if(pidholder == 0)
pause();
else if(pidholder > 0) {
curr->pid = pidholder;
curr->next = tmp;
tmp = curr;
count = count + 1;
}
}
curr = tmp;
while(curr) {
pidholder = curr->pid;
kill(pidholder, SIGKILL);
tmp = curr;
curr = curr->next;
freenode(tmp);
}
printtotal(count);
exit(0);
}https://stackoverflow.com/questions/26050703
复制相似问题