#include <unistd.h> #include <sys/types.h> #include <stdio.h> #include <errno.h> int main(int argc,char **argv) { pid_t pid,old_ppid,new_ppid; pid_t child,parent; parent=getpid(); if((child=fork())<0){ printf(“fork error”); exit(1); }else if(child==0){ /*此时是子进程被调度运行*/ old_ppid=getppid(); sleep(2); new_ppid=getppid(); } else { sleep(1); exit(0); /*父进程退出,此时子进程 会被只派一个新的父进程PID,值为1*/ } printf("Original parent:%d\n",parent); printf("Child:%d\n",getpid()); printf("Child's old ppid:%d\n",old_ppid); printf("Child's new ppid:%d\n",new_ppid); exit(0);}
时间: 2023-06-16 09:06:42 浏览: 63
这是一个简单的进程创建和进程间通信的程序,使用了fork()和getppid()函数。
程序先创建了一个父进程,然后通过fork()函数创建了一个子进程。子进程在运行时先用getppid()函数获取其父进程的PID,然后睡眠2秒钟,再次获取其父进程的PID。父进程在创建子进程后睡眠1秒钟,然后退出。
程序输出了原始父进程的PID、子进程的PID、子进程的旧父进程的PID和子进程的新父进程的PID。
当子进程运行时,它的父进程已经退出,所以它的新父进程的PID为1。
相关问题
#include <fcntl.h> #include <unistd> #include <sys/ioctl> #include <sys/time>qt里面定义出错
#include <fcntl.h>是C/C++中的一个头文件,定义了一些文件控制相关的宏和函数。例如,open()函数就是在这个头文件中定义的。在使用这个头文件时,需要注意一些编译器的不同,可能会导致一些定义出现错误。同时,<unistd.h>和<sys/ioctl.h>也是一些常用的系统调用头文件。而<sys/types.h>、<sys/socket.h>、<netdb.h>、<stdio.h>、<stdlib.h>、<string.h>、<ctype.h>、<errno.h>、<malloc.h>、<netinet/in.h>、<arpa/inet.h>、<stdarg.h>等头文件也都是C/C++中常用的头文件,定义了很多系统调用函数和宏。
关于在Qt中出现include头文件定义错误,可能是因为Qt中的一些宏与C/C++中常用的宏冲突了,需要进行一些修改和调整。
/* Socket head file */ #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h>/*sockaddr_in{}*/ #include<arpa/inet.h> /* Unix standard head file */ #include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include <errno.h>/* strerror(),perror(),errno head file*/ #include <sys/time.h> #include <sys/wait.h> #define MAXBUFF 1024 #define PORT 9999怎么改成windows系统
在Windows系统中,网络编程需要使用Winsock API,因此需要引入`<winsock2.h>`头文件。此外,需要在程序中调用`WSAStartup()`函数和`WSACleanup()`函数来初始化和释放Winsock库。
下面是在Windows系统下进行网络编程的头文件和常量定义示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#define MAXBUFF 1024
#define PORT 9999
```
其中,`<ws2tcpip.h>`头文件包含了一些网络编程相关的函数和结构体定义。`#pragma comment(lib, "Ws2_32.lib")`语句用于链接Winsock库。
需要注意的是,在Windows系统中,端口号的类型为`unsigned short`,而不是`int`。因此,定义端口号常量时应该使用`USHORT`类型:
```c
#define PORT (USHORT)9999
```