pid_t fork
(void);
intexecl
(const
char
* path,
const
char
* arg,..
.);int
kill
(pid_t pid,
int sig)
;
fork
1
建立乙個子程序,一般情況子程序的pid和父程序的pid相差1,所在標頭檔案#include
。
這個函式的返回值很重要,在父程序中返回子程序的pid,在子程序中返回0,大多都是以這樣的方式來判斷是否是子程序和父程序。
重要的事情:
如果使用gdb時,斷點只會在父程序中生效
pid_t 的型別,從下面**可以看出來大部分情況應該pid_t型別為int, 就算不一樣也應該為長整形等可以隱式轉換的型別,大部分情況也不會損失精度。可以直接用int
儲存返回值。
#define __s32_type int
# define __std_type typedef
#define __pid_t_type __s32_type
__std_type __pid_t_type __pid_t;
/* type of process identifications. */
typedef __pid_t pid_t;
execl
2
是執行檔案函式,所在標頭檔案#include
。
網上大多數的引數說明都是說:第乙個引數是executable path,後面跟著若干個入參。
實際情況:
引數一 : executable path + executable file name。
引數二 : executable的第乙個入參,也就是 agrs[0],一般第乙個入參就是可執行檔名。
引數三~n-1: 多個入參。
引數n : 需要最後乙個入參為空標識結束位置,c語言用null,c++ 用nullptr。
重要的事情:
第乙個入參即為程序名字,如用ps aux |grep
檢視程序時,並非是execl
的第乙個引數,第乙個引數只表示可執行檔案的路徑和名字,第乙個入參才是程序名。
該系統呼叫是用新的可執行程式程序替換當前程序,如果失敗會返回到呼叫程序,成功則呼叫程序銷毀,新的執行執行緒執行。
kill
3
傳送乙個訊號到乙個程式,因為這裡是要結束程序,所以這裡就使用sigkill
發生讓程式結束的訊號到作業系統。
引數一 : pid
引數二 : linux signal
簡單的測試**:
fork(2) - linux man page . ↩︎#include
#include
#include
#include
#include
#include
#include
"common.h"
#include
//父程序
enum
class
processtype
;void
switchprocess
(processtype type, tint32 pid)
}else
if(type == processtype::ksubprocess)
}int
main()
else
tint32 ret =
kill
(id, sigkill)
;railog
("kill subprocess %d, result :%d"
,id,ret)
;for
(int i =
0; i <
5; i++
)return0;
}//子程序
#include
#include
#include
"common.h"
intmain
(tint32 n, tint8*
* args)
std::this_thread::
sleep_for
(std::chrono::
seconds(1
));}
return0;
}//cmakefile
cmake_minimum_required
( version version 3.16
)project
(test-create-subprocess)
set (cmake_cxx_standard 17
)add_definitions
(-g -wall)
add_executable
( testfork
testfork.cpp
)add_executable
( subprocess
subprocess.cpp
)
execl(3) - linux man page. ↩︎
kill(2) - linux man page. ↩︎
linux建立子程序
include include include intmain int argc,char ar else if pid 0 else if pid 0 return0 include include include intmain int argc,char ar else if pid 0 el...
建立子程序並傳遞引數
1 from multiprocessing import process2 import os 3from time import sleep4 定義任務的函式 5def run test name,age,kwargs 6print 子程序正在執行 name值 s age值 d name,age...
C 下查詢並殺死子程序 程序樹
參考 如何殺死程序及子程序 傳入引數 父程序id public static void killprocessandchildren int pid trycatch argumentexception 常用的process方法 1.根據程序id,獲得程序 process p process.get...