環境:Vmware Workstation;CentOS-6.4-x86_64
說明:
1、execve函數執行的本質是:在程序1中執行execve函數調用程序2,那麼程序2就會完全霸佔程序1的內存空間,從而實現一個程序調用另一個程序。
2、通過execve調用的程序,兩個進程的PID是完全一樣的。
圖解說明:
程序說明:驗證通過execve調用的程序的進程PID相同。
步驟:
1、編寫makefile文件:
.SUFFIXES:.c .o
CC=gcc
SRCS1=main.c
OBJS1=$(SRCS1:.c=.o)
EXEC1=main
SRCS2=other.c
OBJS2=$(SRCS2:.c=.o)
EXEC2=other
start: $(OBJS1) $(OBJS2)
$(CC) -o $(EXEC1) $(OBJS1)
$(CC) -o $(EXEC2) $(OBJS2)
@echo "-----------------------------OK-----------------------"
.c.o:
$(CC) -Wall -o $@ -c $<
clean:
rm -rf $(EXEC1) $(OBJS1)
rm -rf $(EXEC2) $(OBJS2)
2、編寫源文件other.c:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int arg, char *args[])
{
int id = getpid();
printf("other PID = %d\n", id);
return 0;
}
3、編寫源文件main.c:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
// 得到進程的PID
printf("main PID = %d\n", getpid());
// 定義字符數組,保存程序執行的參數
char *args[] = { "/home/negivup/mycode/other", NULL };
// 調用execve執行程序
execve("/home/negivup/mycode/other", args, NULL);
return 0;
}
4、編譯並執行程序:[negivup@negivup mycode]$ make
gcc -Wall -o main.o -c main.c
gcc -Wall -o other.o -c other.c
gcc -o main main.o
gcc -o other other.o
-----------------------------OK-----------------------
[negivup@negivup mycode]$ main
main PID = 8179
other PID = 8179
從程序的執行效果中可以看出,進程main和進程other的PID是相同的。
PS:根據傳智播客視頻學習整理得出。