linux – 通过/ dev / pts在另一个终端中执行命令

前端之家收集整理的这篇文章主要介绍了linux – 通过/ dev / pts在另一个终端中执行命令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用STDIN 3的终端(/ proc / xxxx / fd / 0 – > / dev / pts / 3)

所以如果(在另一个终端)我这样做:

echo 'do_something_command' > /dev/pts/3

该命令显示在我的第一个(pts / 3)终端中,但该命令未执行.如果(在这个终端pts / 3中)我在一个程序中等待来自stdin的一些数据,数据被写在屏幕上,但程序没有从stdin中捕获它.

我想要做的是执行命令“do_something_command”,而不仅仅是显示它.

有人可以向我解释这种行为吗?我如何实现我的意图?

解决方法

我完全得到了你的要求.您可以通过在C中编写和执行一小段代码来实现此目的.这应该会给你一些想法.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>

void print_help(char *prog_name) {
        printf("Usage: %s [-n] DEVNAME COMMAND\n",prog_name);
        printf("Usage: '-n' is an optional argument if you want to push a new line at the end of the text\n");
        printf("Usage: Will require 'sudo' to run if the executable is not setuid root\n");
        exit(1);
}

int main (int argc,char *argv[]) {
    char *cmd,*nl = "\n";
    int i,fd;
    int devno,commandno,newline;
    int mem_len;
    devno = 1; commandno = 2; newline = 0;
    if (argc < 3) {
        print_help(argv[0]);
    }
    if (argc > 3 && argv[1][0] == '-' && argv[1][1] == 'n') {
        devno = 2; commandno = 3; newline=1;
    } else if (argc > 3 && argv[1][0] == '-' && argv[1][1] != 'n') {
        printf("Invalid Option\n");
        print_help(argv[0]);
    }
    fd = open(argv[devno],O_RDWR);
    if(fd == -1) {
        perror("open DEVICE");
        exit(1);
    }
    mem_len = 0;
    for ( i = commandno; i < argc; i++ ) {
        mem_len += strlen(argv[i]) + 2;
        if ( i > commandno ) {
            cmd = (char *)realloc((void *)cmd,mem_len);
        } else { //i == commandno
            cmd = (char *)malloc(mem_len);
        }

        strcat(cmd,argv[i]);
        strcat(cmd," ");
    }
  if (newline == 0)
        usleep(225000);
    for (i = 0; cmd[i]; i++)
        ioctl (fd,TIOCSTI,cmd+i);
    if (newline == 1)
        ioctl (fd,nl);
    close(fd);
    free((void *)cmd);
    exit (0);
}

使用sudo权限编译并执行它.例如,如果你想在/ dev / pts / 3上执行命令,那么只需执行一个sudo ./a.out -n / dev / pts / 3 whoami,在/ dev / pts / 3上运行whoami.

代码完全取自this page.

原文链接:https://www.f2er.com/linux/394732.html

猜你在找的Linux相关文章