- 论坛徽章:
- 0
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
void sig_child(int signo)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
int main(int argc, char **argv)
{
int aa = 10;
int pids[100] = {0};
int index = 0;
signal(SIGCHLD, sig_child);
char *hello = (char*)malloc(100*sizeof(char));
memset(hello, 0x00, 100*sizeof(char));
while(index < 10)
{
getchar();
pid_t chpid = fork();
if(chpid != 0)
{
pids[index++] = chpid;
continue;
}
sprintf(hello, "%d", getpid());
while(index-- > 0)
{
pids[index] = 0;
}
if(chpid == 0)
{
printf("%04x %d %s %dn", hello, getpid(), hello, strlen(hello));
sleep(10);
printf("%04x %d %s %dn", hello, getpid(), hello, strlen(hello));
break;
}
}
free(hello);
while(index-- > 0)
{
printf("%dn", pids[index]);
}
return 0;
}
|
关于priintf的那两句,有个疑问:
多进程会把动态分配的内存也拷贝一份么?打印出来hello指向的地址是为什么一样的,却可以存放不同的内容?
附上输入:
82de008 20981 20981 5
82de008 20982 20982 5
82de008 20987 20987 5
82de008 20988 20988 5
82de008 20993 20993 5
82de008 20994 20994 5
82de008 20995 20995 5
82de008 21000 21000 5
82de008 21001 21001 5
82de008 20981 20981 5
82de008 20982 20982 5
82de008 20987 20987 5
82de008 20988 20988 5
82de008 20993 20993 5
82de008 20994 20994 5
82de008 20995 20995 5
82de008 21000 21000 5
82de008 21001 21001 5
[ 本帖最后由 onmeiei 于 2009-12-7 19:32 编辑 ] |
|