環境:Vmware Workstation;CentOS-6.4-x86_64
程序的實現原理:
在myexecve中得到文件的描述符,通過execve函數,傳遞文件的描述符到程序other中,隨後通過程序other替換程序myexecve,最後實現不同進程之間完成共享文件描述符的操作。
步驟:
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、編寫需要用到的文本文件a.txt:This is some words.
3、編寫源文件other.c:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int arg, char *args[])
{
// 通過傳遞的參數獲取文件描述符
char *file_num = args[1];
// 把字符串轉換成數字
int fd = atoi(file_num);
// 定義一個字符數組用來存儲讀取到的信息
char buf[1024];
// 清空緩衝區內存
memset(buf, 0, sizeof(buf));
// 通過文件描述符讀取文件的信息
read(fd, buf, sizeof(buf));
// 輸出信息到屏幕
printf("%s", buf);
return 0;
}
4、編寫源文件main.c:#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
// 打開文件,得到文件描述符
int fd = open("a.txt", O_RDONLY);
// 判斷文件是否打開成功
if (fd == -1)
{
printf("File open failed : %s\n", strerror(errno));
}
// 定義一個字符數組用來存儲文件描述符
char file_tar[10];
// 初始化字符數組
memset(file_tar, 0, sizeof(file_tar));
// 將文件描述符轉成字符串
sprintf(file_tar, "%d", fd);
// 定義一個字符指針數組,作爲execve函數的參數
// 設置字符指針數組的第一個參數是程序的名字
// 設置字符指針數組的第二個參數是文件操作符
// 設置字符指針數組的第三個參數是NULL
char *char_str[3] = { "other", file_tar, NULL };
// 通過函數execve調用程序other
execve("other", char_str, NULL);
// 關閉文件描述符
close(fd);
return 0;
}
5、編譯並執行程序:[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
This is some words.
可以從程序的執行效果中看出,兩個進程之間共享了文件描述符。
PS:根據傳智播客視頻學習整理得出。