当前位置: 技术问答>linux和unix
多进程 管道问题
来源: 互联网 发布时间:2017-05-08
本文导语: Pipe3.c #include #include #include #include int main(int argc, char** argv) { int data_processed; int file_pipes[2]; const char some_data[] = "123"; char buffer[BUFSIZ + 1]; pid_t fork_result; memset(buffer, ''...
Pipe3.c
#include
#include
#include
#include
int main(int argc, char** argv)
{
int data_processed;
int file_pipes[2];
const char some_data[] = "123";
char buffer[BUFSIZ + 1];
pid_t fork_result;
memset(buffer, '', sizeof(buffer));
if(pipe(file_pipes) == 0)
{
fork_result = fork();
if(-1 == fork_result)
{
fprintf(stdout, "Fork failuren");
exit(EXIT_FAILURE);
}
else if(0 == fork_result)
{
sprintf(buffer, "%d", file_pipes[0]);
printf("buffer address 0x%04Xn", buffer);
(void)execl("pipe4", "pipe4", buffer, (char*)0);
printf("execl failuren");
exit(EXIT_FAILURE);
}
else
{
data_processed = write(file_pipes[1], some_data, strlen(some_data));
printf("Write %d bytesn", data_processed);
wait(NULL);
printf("Child stoppedn");
}
}
exit(EXIT_SUCCESS);
}
pile4.c:
#include
#include
#include
#include
int main(int argc, char** argv)
{
int data_processed;
char buffer[BUFSIZ + 1];
int file_descriptor;
memset(buffer, '', sizeof(buffer));
sscanf(argv[1], "%d", &file_descriptor);
printf("argv[1] address 0x%04Xn", argv[1]);
data_processed = read(file_descriptor, buffer, BUFSIZ);
printf("%d - read %d bytes: %sn", getpid(), data_processed, buffer);
sleep(15);
exit(EXIT_SUCCESS);
}
其中:
1.(void)execl("pipe4", "pipe4", buffer, (char*)0);
将会替换当前的进程, 是不是buffer指向的栈空间的资源也是放掉了,那pipe4为什么还能通过argv[1]得到内容??
3. pipe3.c中buffer指向的内存地址和argv[1]指向的内存地址是什么关系???
#include
#include
#include
#include
int main(int argc, char** argv)
{
int data_processed;
int file_pipes[2];
const char some_data[] = "123";
char buffer[BUFSIZ + 1];
pid_t fork_result;
memset(buffer, '', sizeof(buffer));
if(pipe(file_pipes) == 0)
{
fork_result = fork();
if(-1 == fork_result)
{
fprintf(stdout, "Fork failuren");
exit(EXIT_FAILURE);
}
else if(0 == fork_result)
{
sprintf(buffer, "%d", file_pipes[0]);
printf("buffer address 0x%04Xn", buffer);
(void)execl("pipe4", "pipe4", buffer, (char*)0);
printf("execl failuren");
exit(EXIT_FAILURE);
}
else
{
data_processed = write(file_pipes[1], some_data, strlen(some_data));
printf("Write %d bytesn", data_processed);
wait(NULL);
printf("Child stoppedn");
}
}
exit(EXIT_SUCCESS);
}
pile4.c:
#include
#include
#include
#include
int main(int argc, char** argv)
{
int data_processed;
char buffer[BUFSIZ + 1];
int file_descriptor;
memset(buffer, '', sizeof(buffer));
sscanf(argv[1], "%d", &file_descriptor);
printf("argv[1] address 0x%04Xn", argv[1]);
data_processed = read(file_descriptor, buffer, BUFSIZ);
printf("%d - read %d bytes: %sn", getpid(), data_processed, buffer);
sleep(15);
exit(EXIT_SUCCESS);
}
其中:
1.(void)execl("pipe4", "pipe4", buffer, (char*)0);
将会替换当前的进程, 是不是buffer指向的栈空间的资源也是放掉了,那pipe4为什么还能通过argv[1]得到内容??
3. pipe3.c中buffer指向的内存地址和argv[1]指向的内存地址是什么关系???
|
1 是的!资源释放掉了! 得到内容是因为内核已经把数据拷贝过去
2 没有关系!
2 没有关系!