如何在C / C ++上在Linux操作系统上启动进程 [英] How to start process on Linux OS in C, C++
问题描述
我有无线USB适配器,我使用pstree命令来监视所有进程。
当我插入USB适配器到我的Linux操作系统时,我看到新的进程wpa_supplicant与pstree命令。
我使用C / C ++语言。我知道Linux操作系统将使用NetworkManager守护程序来监控网络(eth,蓝牙,wifi等),但我不知道如何我们可以启动wpa_supplicant?我可以使用dbus或systemd吗?
感谢
Thong LT
使用fork()系统调用,它将创建一个子进程或者如果你想通过C代码运行可执行文件,然后使用exec()库函数并指定可执行文件的路径。
这里是代码:
#include< unistd.h>
#include< stdio.h>
#include< sys / types.h>
#include< stdlib.h>
#include< sys / wait.h>
int main(){
pid_t pid,p;
int i,status;
printf(Parent process starting with PID =%d it's Parent ID%d\\\
,(int)getpid(),(int)getppid());
if((pid = fork())== - 1){
fprintf(stderr,FORK FAILED\\\
);
return -1;
}
if(pid == 0){
printf(Child process starting with PID =%d\\\
,(int)getpid());
for(i = 0; i <5; i ++){
printf(Child prints [%d] \\\
,i);
sleep(2);
}
_exit(0);
// exit(0);
}
else {
p = wait(& status);
printf(父继续执行,从子进程控制%d \\\
,(int)p);
// printf(孩子的返回状态是%d \\\
,status);
for(i = 0; i <5; i ++){
sleep(2);
printf(Parent prints [%d] \\\
,i);
// sleep(2);
}
_exit(0);
}
return 0;
}
I have wireless USB Adapter and I use "pstree" command to monitor all processes.
When I plug the USB adapter into my Linux OS I see new process "wpa_supplicant" with "pstree" command.
I use in C/C++ language . I know Linux OS will use "NetworkManager" daemon to monitor network (eth, bluetooth, wifi. etc) but i don't know How to we can start "wpa_supplicant" ? Can i use dbus or systemd?
Thanks Thong LT
Use fork() system call and it will create a child process or if you want to run the executable through C code then use exec() library function and specify the path of the executable.
Here is the code:
#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/wait.h>
int main() {
pid_t pid,p;
int i,status;
printf("Parent process starts with PID = %d it's Parent ID %d\n",(int)getpid(),(int)getppid());
if((pid = fork())==-1) {
fprintf(stderr,"FORK FAILED\n");
return -1;
}
if(pid == 0 ) {
printf("Child process starts with PID = %d\n",(int)getpid());
for(i = 0 ; i < 5; i++) {
printf("Child prints [%d]\n",i);
sleep(2);
}
_exit(0);
//exit(0);
}
else {
p = wait(&status);
printf("Parent resumes execution, took control from the child %d \n",(int)p);
//printf("Return status of the child is %d\n",status);
for(i = 0; i< 5 ; i++) {
sleep(2);
printf("Parent prints [%d]\n",i);
//sleep(2);
}
_exit(0);
}
return 0;
}
这篇关于如何在C / C ++上在Linux操作系统上启动进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!