小编Byr*_*sco的帖子

编写自己的shell代码在处理某些管道时挂起 - 在C中

我现在正在编写自己的shell作为一个类的项目,并且一切都在工作.我的问题是我的管道,有时他们工作,有时,他们只是挂起,直到我打断他们.我已经对此进行了研究,似乎写入stdin的函数没有从第一个进程接收到EOF; 通常我已经知道问题是管道没有被关闭,但我的代码并不是这种情况(据我所知).

所有重定向工作及其任何变化:

  • ls -l > file1
  • wc < file1 > file2

以下管道命令有效:

  • w | head -n 4
  • w | head -n 4 > file1

这不起作用:ls | grep file1它显示正确的输出并且永远不会结束,除非用户向其发送中断信号.ls | grep file1 > file2也行不通.它挂起而不显示输出,创建file2,但从不写入它.

无论如何,我希望有一些我错过了别人可以注意到的东西; 我已经有一段时间了.如果我能提供更多代码,请告诉我.我在下面发布的代码是主文件,没有删除.

/*
 * This code implemenFts a simple shell program
 * At this time it supports just simple commands with 
 * any number of args.
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include …
Run Code Online (Sandbox Code Playgroud)

c linux redirect fork pipe

2
推荐指数
1
解决办法
4277
查看次数

Linux C套接字服务器printf问题

我这里有一个简单的套接字服务器,看起来应该是一个简单的问题.在套接字接受连接之前,我希望它打印其进程ID.但它不会打印任何东西,无论它是什么,直到有连接.起初我以为这是因为接受调用以某种方式阻止了打印,所以我尝试在各个地方添加它:

int fdflags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, fdflags | O_NONBLOCK);
Run Code Online (Sandbox Code Playgroud)

但除了使接受非阻塞之外,这对代码没有影响.所以我希望这里的某个人能告诉我发生了什么.否则服务器工作.我会继续发布客户端代码.

server.c:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>

static void error(char *msg) {
    perror(msg);
    exit(1);
}

static void SIGCHLD_Handler(int sig) {
    waitpid(-1, NULL, WNOHANG);
}

int main(int argc, char *argv[]) {

    int num,sockfd, newsockfd, portno, clilen;
    char buffer[256];
    struct sockaddr_in serv_addr, cli_addr;
    struct sigaction sigact;

    sigact.sa_handler = SIGCHLD_Handler; …
Run Code Online (Sandbox Code Playgroud)

c sockets printf

1
推荐指数
1
解决办法
5471
查看次数

标签 统计

c ×2

fork ×1

linux ×1

pipe ×1

printf ×1

redirect ×1

sockets ×1