我想派生一个打开套接字的子程序。
我已经编写了打开套接字,接收数据并打印其接收到的数据的代码。 GUI使用
Tk
下面是代码,除了没有分叉new_port
子例程外,它基本上完成了我想做的事情。每次单击submit
按钮时,Tk
窗口都会卡住。我正在寻求将fork
子例程添加到new_port
子例程中的帮助,因此它会产生一个新的子进程。我个人在执行fork
时遇到语法错误或无法将套接字推入子进程的麻烦。
我的想法是我可以在表单中填写一个新端口,然后单击“提交”。窗口关闭,然后我按new再次放入新端口,现在第二个插座与第一个插座同时打开。例如同时监听端口1234和5678。
#!/usr/bin/perl -w
use IO::Socket::INET;
use Tk;
$myip = `ifconfig | grep -i inet | head -1 | cut -d ":" -f2 | cut -d " " -f1`;
sub new_port {
my $socket = new IO::Socket::INET(
LocalHost => "$myip",
LocalPort => "$myport",
Proto => 'tcp' Reuse => 1
);
die "Cannot create socket on local host" unless $socket;
print "Server waiting for client connection on port $myport\n";
while ( 1 ) {
my $client_socket = $socket->accept();
my $client_address = $client_socket->peerhost();
my $client_port = $client_socket->peerport();
my $input_data = "";
my $received_data = "";
do {
$client_socket->recv($received_data, 65536);
$input_data = $input_data . $received_data;
} while ( $received_data ne "" );
print "INPUT----------------------------------\n";
print "Data from $client_address on port $client_port\n";
print $input_data;
shutdown($client_socket, 1);
}
}
sub new_port_window {
my $sw = MainWindow->new;
$sw->geometry("200x100");
$sw->title("port opener");
$sw->Label(
-text "Insert port #"
)->place(
-anchor => 'center',
-relx => 0.5,
-rely => 0.2
);
$sw->Entry(
-bg => 'white',
-fg => 'black',
-textvariable => \$myport
)->place(
-anchor => 'center',
-relx => 0.5,
-rely => 0.4
);
$sw->Button(
-text "submit",
-command => sub {new_port}
)->place(
width => 100,
-anchor => "center",
-relx => 0.5,
-rely => 0.8
);
}
my $mw = MainWindow->new;
$mw->geometry("150x100");
$mw->title("GUI TEST NEW FUNCTION");
$mw->Label(
-text => "click new"
)->place(
-anchor => "center",
-relx => 0.5,
-rely => 0.3
);
$mw->Button(
-text => "NEW",
-command => sub {new_port_window}
)->place(
-width => 50,
-anchor => "center",
-relx => 0.5,
-rely => 0.8
);
MainLoop;
答案 0 :(得分:3)
自从我第一次尝试以来已经很长时间了,所以我忘记了这是必须完成的方式,还是仅仅是许多工作方式中的一种,但是要旨是:
shutdown
由于您只想将数据从父级发送到子级,因此看起来像
($sock_child, $sock_par) = IO::Socket->socketpair(
Socket::AF_UNIX, Socket::SOCK_STREAM, Socket::PF_UNSPEC);
$pid = fork;
if ($pid) {
# parent
shutdown($sock_par, 0); # no more reading from parent
print $sock_par $data_to_pass_to_child;
...
} else {
# child
shutdown($sock_child, 1); # no more writing in child
$data_from_parent = <$sock_child>;
...
}