Backport 2010-03-25T08:48:52Z!mituharu@math.s.chiba-u.ac.jp from trunk
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <signal.h>
24
25 /* This file is split into two parts by the following preprocessor
26 conditional. The 'then' clause contains all of the support for
27 asynchronous subprocesses. The 'else' clause contains stub
28 versions of some of the asynchronous subprocess routines that are
29 often called elsewhere in Emacs, so we don't have to #ifdef the
30 sections that call them. */
31
32 \f
33 #ifdef subprocesses
34
35 #include <stdio.h>
36 #include <errno.h>
37 #include <setjmp.h>
38 #include <sys/types.h> /* some typedefs are used in sys/file.h */
39 #include <sys/file.h>
40 #include <sys/stat.h>
41 #include <setjmp.h>
42 #ifdef HAVE_INTTYPES_H
43 #include <inttypes.h>
44 #endif
45 #ifdef STDC_HEADERS
46 #include <stdlib.h>
47 #endif
48
49 #ifdef HAVE_UNISTD_H
50 #include <unistd.h>
51 #endif
52 #include <fcntl.h>
53
54 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
55 #include <sys/socket.h>
56 #include <netdb.h>
57 #include <netinet/in.h>
58 #include <arpa/inet.h>
59
60 /* Are local (unix) sockets supported? */
61 #if defined (HAVE_SYS_UN_H)
62 #if !defined (AF_LOCAL) && defined (AF_UNIX)
63 #define AF_LOCAL AF_UNIX
64 #endif
65 #ifdef AF_LOCAL
66 #define HAVE_LOCAL_SOCKETS
67 #include <sys/un.h>
68 #endif
69 #endif
70 #endif /* HAVE_SOCKETS */
71
72 #if defined(BSD_SYSTEM)
73 #include <sys/ioctl.h>
74 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
75 #include <fcntl.h>
76 #endif /* HAVE_PTYS and no O_NDELAY */
77 #endif /* BSD_SYSTEM */
78
79 #ifdef NEED_BSDTTY
80 #include <bsdtty.h>
81 #endif
82
83 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
84 #ifdef HAVE_SOCKETS
85 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
86 /* sys/ioctl.h may have been included already */
87 #ifndef SIOCGIFADDR
88 #include <sys/ioctl.h>
89 #endif
90 #include <net/if.h>
91 #endif
92 #endif
93
94 #ifdef HAVE_SYS_WAIT
95 #include <sys/wait.h>
96 #endif
97
98 #ifdef HAVE_RES_INIT
99 #include <netinet/in.h>
100 #include <arpa/nameser.h>
101 #include <resolv.h>
102 #endif
103
104 #include "lisp.h"
105 #include "systime.h"
106 #include "systty.h"
107
108 #include "window.h"
109 #include "buffer.h"
110 #include "character.h"
111 #include "coding.h"
112 #include "process.h"
113 #include "frame.h"
114 #include "termhooks.h"
115 #include "termopts.h"
116 #include "commands.h"
117 #include "keyboard.h"
118 #include "blockinput.h"
119 #include "dispextern.h"
120 #include "composite.h"
121 #include "atimer.h"
122
123 #if defined (USE_GTK) || defined (HAVE_GCONF)
124 #include "xgselect.h"
125 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
126
127 Lisp_Object Qprocessp;
128 Lisp_Object Qrun, Qstop, Qsignal;
129 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
130 Lisp_Object Qlocal, Qipv4, Qdatagram, Qseqpacket;
131 Lisp_Object Qreal, Qnetwork, Qserial;
132 #ifdef AF_INET6
133 Lisp_Object Qipv6;
134 #endif
135 Lisp_Object QCport, QCspeed, QCprocess;
136 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
137 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
138 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
139 Lisp_Object QClocal, QCremote, QCcoding;
140 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
141 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
142 Lisp_Object Qlast_nonmenu_event;
143 /* QCfamily is declared and initialized in xfaces.c,
144 QCfilter in keyboard.c. */
145 extern Lisp_Object QCfamily, QCfilter;
146
147 /* Qexit is declared and initialized in eval.c. */
148
149 /* QCfamily is defined in xfaces.c. */
150 extern Lisp_Object QCfamily;
151 /* QCfilter is defined in keyboard.c. */
152 extern Lisp_Object QCfilter;
153
154 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
155 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
156 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
157 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
158
159 #ifdef HAVE_SOCKETS
160 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
161 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
162 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
163 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
164 #else
165 #define NETCONN_P(p) 0
166 #define NETCONN1_P(p) 0
167 #define SERIALCONN_P(p) 0
168 #define SERIALCONN1_P(p) 0
169 #endif /* HAVE_SOCKETS */
170
171 /* Define first descriptor number available for subprocesses. */
172 #define FIRST_PROC_DESC 3
173
174 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
175 testing SIGCHLD. */
176
177 #if !defined (SIGCHLD) && defined (SIGCLD)
178 #define SIGCHLD SIGCLD
179 #endif /* SIGCLD */
180
181 #include "syssignal.h"
182
183 #include "syswait.h"
184
185 extern char *get_operating_system_release ();
186
187 /* Serial processes require termios or Windows. */
188 #if defined (HAVE_TERMIOS) || defined (WINDOWSNT)
189 #define HAVE_SERIAL
190 #endif
191
192 #ifdef HAVE_SERIAL
193 /* From sysdep.c or w32.c */
194 extern int serial_open (char *port);
195 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
196 #endif
197
198 #ifndef USE_CRT_DLL
199 extern int errno;
200 #endif
201
202 #ifndef HAVE_H_ERRNO
203 extern int h_errno;
204 #endif
205
206 /* t means use pty, nil means use a pipe,
207 maybe other values to come. */
208 static Lisp_Object Vprocess_connection_type;
209
210 /* These next two vars are non-static since sysdep.c uses them in the
211 emulation of `select'. */
212 /* Number of events of change of status of a process. */
213 int process_tick;
214 /* Number of events for which the user or sentinel has been notified. */
215 int update_tick;
216
217 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
218
219 #ifdef BROKEN_NON_BLOCKING_CONNECT
220 #undef NON_BLOCKING_CONNECT
221 #else
222 #ifndef NON_BLOCKING_CONNECT
223 #ifdef HAVE_SOCKETS
224 #ifdef HAVE_SELECT
225 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
226 #if defined (O_NONBLOCK) || defined (O_NDELAY)
227 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
228 #define NON_BLOCKING_CONNECT
229 #endif /* EWOULDBLOCK || EINPROGRESS */
230 #endif /* O_NONBLOCK || O_NDELAY */
231 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
232 #endif /* HAVE_SELECT */
233 #endif /* HAVE_SOCKETS */
234 #endif /* NON_BLOCKING_CONNECT */
235 #endif /* BROKEN_NON_BLOCKING_CONNECT */
236
237 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
238 this system. We need to read full packets, so we need a
239 "non-destructive" select. So we require either native select,
240 or emulation of select using FIONREAD. */
241
242 #ifdef BROKEN_DATAGRAM_SOCKETS
243 #undef DATAGRAM_SOCKETS
244 #else
245 #ifndef DATAGRAM_SOCKETS
246 #ifdef HAVE_SOCKETS
247 #if defined (HAVE_SELECT) || defined (FIONREAD)
248 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
249 #define DATAGRAM_SOCKETS
250 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
251 #endif /* HAVE_SELECT || FIONREAD */
252 #endif /* HAVE_SOCKETS */
253 #endif /* DATAGRAM_SOCKETS */
254 #endif /* BROKEN_DATAGRAM_SOCKETS */
255
256 #if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
257 # define HAVE_SEQPACKET
258 #endif
259
260 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
261 #ifdef EMACS_HAS_USECS
262 #define ADAPTIVE_READ_BUFFERING
263 #endif
264 #endif
265
266 #ifdef ADAPTIVE_READ_BUFFERING
267 #define READ_OUTPUT_DELAY_INCREMENT 10000
268 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
269 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
270
271 /* Number of processes which have a non-zero read_output_delay,
272 and therefore might be delayed for adaptive read buffering. */
273
274 static int process_output_delay_count;
275
276 /* Non-zero if any process has non-nil read_output_skip. */
277
278 static int process_output_skip;
279
280 /* Non-nil means to delay reading process output to improve buffering.
281 A value of t means that delay is reset after each send, any other
282 non-nil value does not reset the delay. A value of nil disables
283 adaptive read buffering completely. */
284 static Lisp_Object Vprocess_adaptive_read_buffering;
285 #else
286 #define process_output_delay_count 0
287 #endif
288
289
290 #include "sysselect.h"
291
292 static int keyboard_bit_set P_ ((SELECT_TYPE *));
293 static void deactivate_process P_ ((Lisp_Object));
294 static void status_notify P_ ((struct Lisp_Process *));
295 static int read_process_output P_ ((Lisp_Object, int));
296 static void create_pty P_ ((Lisp_Object));
297
298 /* If we support a window system, turn on the code to poll periodically
299 to detect C-g. It isn't actually used when doing interrupt input. */
300 #ifdef HAVE_WINDOW_SYSTEM
301 #define POLL_FOR_INPUT
302 #endif
303
304 static Lisp_Object get_process ();
305 static void exec_sentinel ();
306
307 extern int timers_run;
308 \f
309 /* Mask of bits indicating the descriptors that we wait for input on. */
310
311 static SELECT_TYPE input_wait_mask;
312
313 /* Mask that excludes keyboard input descriptor(s). */
314
315 static SELECT_TYPE non_keyboard_wait_mask;
316
317 /* Mask that excludes process input descriptor(s). */
318
319 static SELECT_TYPE non_process_wait_mask;
320
321 /* Mask for the gpm mouse input descriptor. */
322
323 static SELECT_TYPE gpm_wait_mask;
324
325 #ifdef NON_BLOCKING_CONNECT
326 /* Mask of bits indicating the descriptors that we wait for connect to
327 complete on. Once they complete, they are removed from this mask
328 and added to the input_wait_mask and non_keyboard_wait_mask. */
329
330 static SELECT_TYPE connect_wait_mask;
331
332 /* Number of bits set in connect_wait_mask. */
333 static int num_pending_connects;
334
335 #define IF_NON_BLOCKING_CONNECT(s) s
336 #else
337 #define IF_NON_BLOCKING_CONNECT(s)
338 #endif
339
340 /* The largest descriptor currently in use for a process object. */
341 static int max_process_desc;
342
343 /* The largest descriptor currently in use for keyboard input. */
344 static int max_keyboard_desc;
345
346 /* The largest descriptor currently in use for gpm mouse input. */
347 static int max_gpm_desc;
348
349 /* Non-zero if keyboard input is on hold, zero otherwise. */
350 static int kbd_is_on_hold;
351
352 /* Nonzero means delete a process right away if it exits. */
353 static int delete_exited_processes;
354
355 /* Indexed by descriptor, gives the process (if any) for that descriptor */
356 Lisp_Object chan_process[MAXDESC];
357
358 /* Alist of elements (NAME . PROCESS) */
359 Lisp_Object Vprocess_alist;
360
361 /* Buffered-ahead input char from process, indexed by channel.
362 -1 means empty (no char is buffered).
363 Used on sys V where the only way to tell if there is any
364 output from the process is to read at least one char.
365 Always -1 on systems that support FIONREAD. */
366
367 /* Don't make static; need to access externally. */
368 int proc_buffered_char[MAXDESC];
369
370 /* Table of `struct coding-system' for each process. */
371 static struct coding_system *proc_decode_coding_system[MAXDESC];
372 static struct coding_system *proc_encode_coding_system[MAXDESC];
373
374 #ifdef DATAGRAM_SOCKETS
375 /* Table of `partner address' for datagram sockets. */
376 struct sockaddr_and_len {
377 struct sockaddr *sa;
378 int len;
379 } datagram_address[MAXDESC];
380 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
381 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
382 #else
383 #define DATAGRAM_CHAN_P(chan) (0)
384 #define DATAGRAM_CONN_P(proc) (0)
385 #endif
386
387 /* Maximum number of bytes to send to a pty without an eof. */
388 static int pty_max_bytes;
389
390 /* Nonzero means don't run process sentinels. This is used
391 when exiting. */
392 int inhibit_sentinels;
393
394 #ifdef HAVE_PTYS
395 #ifdef HAVE_PTY_H
396 #include <pty.h>
397 #endif
398 /* The file name of the pty opened by allocate_pty. */
399
400 static char pty_name[24];
401 #endif
402 \f
403 /* Compute the Lisp form of the process status, p->status, from
404 the numeric status that was returned by `wait'. */
405
406 static Lisp_Object status_convert (int);
407
408 static void
409 update_status (p)
410 struct Lisp_Process *p;
411 {
412 eassert (p->raw_status_new);
413 p->status = status_convert (p->raw_status);
414 p->raw_status_new = 0;
415 }
416
417 /* Convert a process status word in Unix format to
418 the list that we use internally. */
419
420 static Lisp_Object
421 status_convert (int w)
422 {
423 if (WIFSTOPPED (w))
424 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
425 else if (WIFEXITED (w))
426 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
427 WCOREDUMP (w) ? Qt : Qnil));
428 else if (WIFSIGNALED (w))
429 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
430 WCOREDUMP (w) ? Qt : Qnil));
431 else
432 return Qrun;
433 }
434
435 /* Given a status-list, extract the three pieces of information
436 and store them individually through the three pointers. */
437
438 static void
439 decode_status (l, symbol, code, coredump)
440 Lisp_Object l;
441 Lisp_Object *symbol;
442 int *code;
443 int *coredump;
444 {
445 Lisp_Object tem;
446
447 if (SYMBOLP (l))
448 {
449 *symbol = l;
450 *code = 0;
451 *coredump = 0;
452 }
453 else
454 {
455 *symbol = XCAR (l);
456 tem = XCDR (l);
457 *code = XFASTINT (XCAR (tem));
458 tem = XCDR (tem);
459 *coredump = !NILP (tem);
460 }
461 }
462
463 /* Return a string describing a process status list. */
464
465 static Lisp_Object
466 status_message (p)
467 struct Lisp_Process *p;
468 {
469 Lisp_Object status = p->status;
470 Lisp_Object symbol;
471 int code, coredump;
472 Lisp_Object string, string2;
473
474 decode_status (status, &symbol, &code, &coredump);
475
476 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
477 {
478 char *signame;
479 synchronize_system_messages_locale ();
480 signame = strsignal (code);
481 if (signame == 0)
482 string = build_string ("unknown");
483 else
484 {
485 int c1, c2;
486
487 string = make_unibyte_string (signame, strlen (signame));
488 if (! NILP (Vlocale_coding_system))
489 string = (code_convert_string_norecord
490 (string, Vlocale_coding_system, 0));
491 c1 = STRING_CHAR ((char *) SDATA (string));
492 c2 = DOWNCASE (c1);
493 if (c1 != c2)
494 Faset (string, make_number (0), make_number (c2));
495 }
496 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
497 return concat2 (string, string2);
498 }
499 else if (EQ (symbol, Qexit))
500 {
501 if (NETCONN1_P (p))
502 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
503 if (code == 0)
504 return build_string ("finished\n");
505 string = Fnumber_to_string (make_number (code));
506 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
507 return concat3 (build_string ("exited abnormally with code "),
508 string, string2);
509 }
510 else if (EQ (symbol, Qfailed))
511 {
512 string = Fnumber_to_string (make_number (code));
513 string2 = build_string ("\n");
514 return concat3 (build_string ("failed with code "),
515 string, string2);
516 }
517 else
518 return Fcopy_sequence (Fsymbol_name (symbol));
519 }
520 \f
521 #ifdef HAVE_PTYS
522
523 /* Open an available pty, returning a file descriptor.
524 Return -1 on failure.
525 The file name of the terminal corresponding to the pty
526 is left in the variable pty_name. */
527
528 static int
529 allocate_pty ()
530 {
531 register int c, i;
532 int fd;
533
534 #ifdef PTY_ITERATION
535 PTY_ITERATION
536 #else
537 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
538 for (i = 0; i < 16; i++)
539 #endif
540 {
541 struct stat stb; /* Used in some PTY_OPEN. */
542 #ifdef PTY_NAME_SPRINTF
543 PTY_NAME_SPRINTF
544 #else
545 sprintf (pty_name, "/dev/pty%c%x", c, i);
546 #endif /* no PTY_NAME_SPRINTF */
547
548 #ifdef PTY_OPEN
549 PTY_OPEN;
550 #else /* no PTY_OPEN */
551 {
552 { /* Some systems name their pseudoterminals so that there are gaps in
553 the usual sequence - for example, on HP9000/S700 systems, there
554 are no pseudoterminals with names ending in 'f'. So we wait for
555 three failures in a row before deciding that we've reached the
556 end of the ptys. */
557 int failed_count = 0;
558
559 if (stat (pty_name, &stb) < 0)
560 {
561 failed_count++;
562 if (failed_count >= 3)
563 return -1;
564 }
565 else
566 failed_count = 0;
567 }
568 # ifdef O_NONBLOCK
569 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
570 # else
571 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
572 # endif
573 }
574 #endif /* no PTY_OPEN */
575
576 if (fd >= 0)
577 {
578 /* check to make certain that both sides are available
579 this avoids a nasty yet stupid bug in rlogins */
580 #ifdef PTY_TTY_NAME_SPRINTF
581 PTY_TTY_NAME_SPRINTF
582 #else
583 sprintf (pty_name, "/dev/tty%c%x", c, i);
584 #endif /* no PTY_TTY_NAME_SPRINTF */
585 if (access (pty_name, 6) != 0)
586 {
587 emacs_close (fd);
588 # ifndef __sgi
589 continue;
590 # else
591 return -1;
592 # endif /* __sgi */
593 }
594 setup_pty (fd);
595 return fd;
596 }
597 }
598 return -1;
599 }
600 #endif /* HAVE_PTYS */
601 \f
602 static Lisp_Object
603 make_process (name)
604 Lisp_Object name;
605 {
606 register Lisp_Object val, tem, name1;
607 register struct Lisp_Process *p;
608 char suffix[10];
609 register int i;
610
611 p = allocate_process ();
612
613 p->infd = -1;
614 p->outfd = -1;
615 p->tick = 0;
616 p->update_tick = 0;
617 p->pid = 0;
618 p->pty_flag = 0;
619 p->raw_status_new = 0;
620 p->status = Qrun;
621 p->mark = Fmake_marker ();
622 p->kill_without_query = 0;
623
624 #ifdef ADAPTIVE_READ_BUFFERING
625 p->adaptive_read_buffering = 0;
626 p->read_output_delay = 0;
627 p->read_output_skip = 0;
628 #endif
629
630 /* If name is already in use, modify it until it is unused. */
631
632 name1 = name;
633 for (i = 1; ; i++)
634 {
635 tem = Fget_process (name1);
636 if (NILP (tem)) break;
637 sprintf (suffix, "<%d>", i);
638 name1 = concat2 (name, build_string (suffix));
639 }
640 name = name1;
641 p->name = name;
642 XSETPROCESS (val, p);
643 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
644 return val;
645 }
646
647 static void
648 remove_process (proc)
649 register Lisp_Object proc;
650 {
651 register Lisp_Object pair;
652
653 pair = Frassq (proc, Vprocess_alist);
654 Vprocess_alist = Fdelq (pair, Vprocess_alist);
655
656 deactivate_process (proc);
657 }
658
659 /* Setup coding systems of PROCESS. */
660
661 void
662 setup_process_coding_systems (process)
663 Lisp_Object process;
664 {
665 struct Lisp_Process *p = XPROCESS (process);
666 int inch = p->infd;
667 int outch = p->outfd;
668 Lisp_Object coding_system;
669
670 if (inch < 0 || outch < 0)
671 return;
672
673 if (!proc_decode_coding_system[inch])
674 proc_decode_coding_system[inch]
675 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
676 coding_system = p->decode_coding_system;
677 if (! NILP (p->filter))
678 ;
679 else if (BUFFERP (p->buffer))
680 {
681 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
682 coding_system = raw_text_coding_system (coding_system);
683 }
684 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
685
686 if (!proc_encode_coding_system[outch])
687 proc_encode_coding_system[outch]
688 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
689 setup_coding_system (p->encode_coding_system,
690 proc_encode_coding_system[outch]);
691 }
692 \f
693 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
694 doc: /* Return t if OBJECT is a process. */)
695 (object)
696 Lisp_Object object;
697 {
698 return PROCESSP (object) ? Qt : Qnil;
699 }
700
701 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
702 doc: /* Return the process named NAME, or nil if there is none. */)
703 (name)
704 register Lisp_Object name;
705 {
706 if (PROCESSP (name))
707 return name;
708 CHECK_STRING (name);
709 return Fcdr (Fassoc (name, Vprocess_alist));
710 }
711
712 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
713 doc: /* Return the (or a) process associated with BUFFER.
714 BUFFER may be a buffer or the name of one. */)
715 (buffer)
716 register Lisp_Object buffer;
717 {
718 register Lisp_Object buf, tail, proc;
719
720 if (NILP (buffer)) return Qnil;
721 buf = Fget_buffer (buffer);
722 if (NILP (buf)) return Qnil;
723
724 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
725 {
726 proc = Fcdr (XCAR (tail));
727 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
728 return proc;
729 }
730 return Qnil;
731 }
732
733 /* This is how commands for the user decode process arguments. It
734 accepts a process, a process name, a buffer, a buffer name, or nil.
735 Buffers denote the first process in the buffer, and nil denotes the
736 current buffer. */
737
738 static Lisp_Object
739 get_process (name)
740 register Lisp_Object name;
741 {
742 register Lisp_Object proc, obj;
743 if (STRINGP (name))
744 {
745 obj = Fget_process (name);
746 if (NILP (obj))
747 obj = Fget_buffer (name);
748 if (NILP (obj))
749 error ("Process %s does not exist", SDATA (name));
750 }
751 else if (NILP (name))
752 obj = Fcurrent_buffer ();
753 else
754 obj = name;
755
756 /* Now obj should be either a buffer object or a process object.
757 */
758 if (BUFFERP (obj))
759 {
760 proc = Fget_buffer_process (obj);
761 if (NILP (proc))
762 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
763 }
764 else
765 {
766 CHECK_PROCESS (obj);
767 proc = obj;
768 }
769 return proc;
770 }
771
772
773 #ifdef SIGCHLD
774 /* Fdelete_process promises to immediately forget about the process, but in
775 reality, Emacs needs to remember those processes until they have been
776 treated by sigchld_handler; otherwise this handler would consider the
777 process as being synchronous and say that the synchronous process is
778 dead. */
779 static Lisp_Object deleted_pid_list;
780 #endif
781
782 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
783 doc: /* Delete PROCESS: kill it and forget about it immediately.
784 PROCESS may be a process, a buffer, the name of a process or buffer, or
785 nil, indicating the current buffer's process. */)
786 (process)
787 register Lisp_Object process;
788 {
789 register struct Lisp_Process *p;
790
791 process = get_process (process);
792 p = XPROCESS (process);
793
794 p->raw_status_new = 0;
795 if (NETCONN1_P (p) || SERIALCONN1_P (p))
796 {
797 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
798 p->tick = ++process_tick;
799 status_notify (p);
800 redisplay_preserve_echo_area (13);
801 }
802 else if (p->infd >= 0)
803 {
804 #ifdef SIGCHLD
805 Lisp_Object symbol;
806 /* Assignment to EMACS_INT stops GCC whining about limited range
807 of data type. */
808 EMACS_INT pid = p->pid;
809
810 /* No problem storing the pid here, as it is still in Vprocess_alist. */
811 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
812 /* GC treated elements set to nil. */
813 Fdelq (Qnil, deleted_pid_list));
814 /* If the process has already signaled, remove it from the list. */
815 if (p->raw_status_new)
816 update_status (p);
817 symbol = p->status;
818 if (CONSP (p->status))
819 symbol = XCAR (p->status);
820 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
821 deleted_pid_list
822 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
823 else
824 #endif
825 {
826 Fkill_process (process, Qnil);
827 /* Do this now, since remove_process will make sigchld_handler do nothing. */
828 p->status
829 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
830 p->tick = ++process_tick;
831 status_notify (p);
832 redisplay_preserve_echo_area (13);
833 }
834 }
835 remove_process (process);
836 return Qnil;
837 }
838 \f
839 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
840 doc: /* Return the status of PROCESS.
841 The returned value is one of the following symbols:
842 run -- for a process that is running.
843 stop -- for a process stopped but continuable.
844 exit -- for a process that has exited.
845 signal -- for a process that has got a fatal signal.
846 open -- for a network stream connection that is open.
847 listen -- for a network stream server that is listening.
848 closed -- for a network stream connection that is closed.
849 connect -- when waiting for a non-blocking connection to complete.
850 failed -- when a non-blocking connection has failed.
851 nil -- if arg is a process name and no such process exists.
852 PROCESS may be a process, a buffer, the name of a process, or
853 nil, indicating the current buffer's process. */)
854 (process)
855 register Lisp_Object process;
856 {
857 register struct Lisp_Process *p;
858 register Lisp_Object status;
859
860 if (STRINGP (process))
861 process = Fget_process (process);
862 else
863 process = get_process (process);
864
865 if (NILP (process))
866 return process;
867
868 p = XPROCESS (process);
869 if (p->raw_status_new)
870 update_status (p);
871 status = p->status;
872 if (CONSP (status))
873 status = XCAR (status);
874 if (NETCONN1_P (p) || SERIALCONN1_P (p))
875 {
876 if (EQ (status, Qexit))
877 status = Qclosed;
878 else if (EQ (p->command, Qt))
879 status = Qstop;
880 else if (EQ (status, Qrun))
881 status = Qopen;
882 }
883 return status;
884 }
885
886 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
887 1, 1, 0,
888 doc: /* Return the exit status of PROCESS or the signal number that killed it.
889 If PROCESS has not yet exited or died, return 0. */)
890 (process)
891 register Lisp_Object process;
892 {
893 CHECK_PROCESS (process);
894 if (XPROCESS (process)->raw_status_new)
895 update_status (XPROCESS (process));
896 if (CONSP (XPROCESS (process)->status))
897 return XCAR (XCDR (XPROCESS (process)->status));
898 return make_number (0);
899 }
900
901 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
902 doc: /* Return the process id of PROCESS.
903 This is the pid of the external process which PROCESS uses or talks to.
904 For a network connection, this value is nil. */)
905 (process)
906 register Lisp_Object process;
907 {
908 /* Assignment to EMACS_INT stops GCC whining about limited range of
909 data type. */
910 EMACS_INT pid;
911
912 CHECK_PROCESS (process);
913 pid = XPROCESS (process)->pid;
914 return (pid ? make_fixnum_or_float (pid) : Qnil);
915 }
916
917 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
918 doc: /* Return the name of PROCESS, as a string.
919 This is the name of the program invoked in PROCESS,
920 possibly modified to make it unique among process names. */)
921 (process)
922 register Lisp_Object process;
923 {
924 CHECK_PROCESS (process);
925 return XPROCESS (process)->name;
926 }
927
928 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
929 doc: /* Return the command that was executed to start PROCESS.
930 This is a list of strings, the first string being the program executed
931 and the rest of the strings being the arguments given to it.
932 For a network or serial process, this is nil (process is running) or t
933 \(process is stopped). */)
934 (process)
935 register Lisp_Object process;
936 {
937 CHECK_PROCESS (process);
938 return XPROCESS (process)->command;
939 }
940
941 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
942 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
943 This is the terminal that the process itself reads and writes on,
944 not the name of the pty that Emacs uses to talk with that terminal. */)
945 (process)
946 register Lisp_Object process;
947 {
948 CHECK_PROCESS (process);
949 return XPROCESS (process)->tty_name;
950 }
951
952 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
953 2, 2, 0,
954 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
955 (process, buffer)
956 register Lisp_Object process, buffer;
957 {
958 struct Lisp_Process *p;
959
960 CHECK_PROCESS (process);
961 if (!NILP (buffer))
962 CHECK_BUFFER (buffer);
963 p = XPROCESS (process);
964 p->buffer = buffer;
965 if (NETCONN1_P (p) || SERIALCONN1_P (p))
966 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
967 setup_process_coding_systems (process);
968 return buffer;
969 }
970
971 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
972 1, 1, 0,
973 doc: /* Return the buffer PROCESS is associated with.
974 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
975 (process)
976 register Lisp_Object process;
977 {
978 CHECK_PROCESS (process);
979 return XPROCESS (process)->buffer;
980 }
981
982 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
983 1, 1, 0,
984 doc: /* Return the marker for the end of the last output from PROCESS. */)
985 (process)
986 register Lisp_Object process;
987 {
988 CHECK_PROCESS (process);
989 return XPROCESS (process)->mark;
990 }
991
992 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
993 2, 2, 0,
994 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
995 A value of t means stop accepting output from the process.
996
997 When a process has a filter, its buffer is not used for output.
998 Instead, each time it does output, the entire string of output is
999 passed to the filter.
1000
1001 The filter gets two arguments: the process and the string of output.
1002 The string argument is normally a multibyte string, except:
1003 - if the process' input coding system is no-conversion or raw-text,
1004 it is a unibyte string (the non-converted input), or else
1005 - if `default-enable-multibyte-characters' is nil, it is a unibyte
1006 string (the result of converting the decoded input multibyte
1007 string to unibyte with `string-make-unibyte'). */)
1008 (process, filter)
1009 register Lisp_Object process, filter;
1010 {
1011 struct Lisp_Process *p;
1012
1013 CHECK_PROCESS (process);
1014 p = XPROCESS (process);
1015
1016 /* Don't signal an error if the process' input file descriptor
1017 is closed. This could make debugging Lisp more difficult,
1018 for example when doing something like
1019
1020 (setq process (start-process ...))
1021 (debug)
1022 (set-process-filter process ...) */
1023
1024 if (p->infd >= 0)
1025 {
1026 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1027 {
1028 FD_CLR (p->infd, &input_wait_mask);
1029 FD_CLR (p->infd, &non_keyboard_wait_mask);
1030 }
1031 else if (EQ (p->filter, Qt)
1032 /* Network or serial process not stopped: */
1033 && !EQ (p->command, Qt))
1034 {
1035 FD_SET (p->infd, &input_wait_mask);
1036 FD_SET (p->infd, &non_keyboard_wait_mask);
1037 }
1038 }
1039
1040 p->filter = filter;
1041 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1042 p->childp = Fplist_put (p->childp, QCfilter, filter);
1043 setup_process_coding_systems (process);
1044 return filter;
1045 }
1046
1047 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1048 1, 1, 0,
1049 doc: /* Returns the filter function of PROCESS; nil if none.
1050 See `set-process-filter' for more info on filter functions. */)
1051 (process)
1052 register Lisp_Object process;
1053 {
1054 CHECK_PROCESS (process);
1055 return XPROCESS (process)->filter;
1056 }
1057
1058 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1059 2, 2, 0,
1060 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1061 The sentinel is called as a function when the process changes state.
1062 It gets two arguments: the process, and a string describing the change. */)
1063 (process, sentinel)
1064 register Lisp_Object process, sentinel;
1065 {
1066 struct Lisp_Process *p;
1067
1068 CHECK_PROCESS (process);
1069 p = XPROCESS (process);
1070
1071 p->sentinel = sentinel;
1072 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1073 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1074 return sentinel;
1075 }
1076
1077 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1078 1, 1, 0,
1079 doc: /* Return the sentinel of PROCESS; nil if none.
1080 See `set-process-sentinel' for more info on sentinels. */)
1081 (process)
1082 register Lisp_Object process;
1083 {
1084 CHECK_PROCESS (process);
1085 return XPROCESS (process)->sentinel;
1086 }
1087
1088 DEFUN ("set-process-window-size", Fset_process_window_size,
1089 Sset_process_window_size, 3, 3, 0,
1090 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1091 (process, height, width)
1092 register Lisp_Object process, height, width;
1093 {
1094 CHECK_PROCESS (process);
1095 CHECK_NATNUM (height);
1096 CHECK_NATNUM (width);
1097
1098 if (XPROCESS (process)->infd < 0
1099 || set_window_size (XPROCESS (process)->infd,
1100 XINT (height), XINT (width)) <= 0)
1101 return Qnil;
1102 else
1103 return Qt;
1104 }
1105
1106 DEFUN ("set-process-inherit-coding-system-flag",
1107 Fset_process_inherit_coding_system_flag,
1108 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1109 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1110 If the second argument FLAG is non-nil, then the variable
1111 `buffer-file-coding-system' of the buffer associated with PROCESS
1112 will be bound to the value of the coding system used to decode
1113 the process output.
1114
1115 This is useful when the coding system specified for the process buffer
1116 leaves either the character code conversion or the end-of-line conversion
1117 unspecified, or if the coding system used to decode the process output
1118 is more appropriate for saving the process buffer.
1119
1120 Binding the variable `inherit-process-coding-system' to non-nil before
1121 starting the process is an alternative way of setting the inherit flag
1122 for the process which will run. */)
1123 (process, flag)
1124 register Lisp_Object process, flag;
1125 {
1126 CHECK_PROCESS (process);
1127 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1128 return flag;
1129 }
1130
1131 DEFUN ("process-inherit-coding-system-flag",
1132 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1133 1, 1, 0,
1134 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1135 If this flag is t, `buffer-file-coding-system' of the buffer
1136 associated with PROCESS will inherit the coding system used to decode
1137 the process output. */)
1138 (process)
1139 register Lisp_Object process;
1140 {
1141 CHECK_PROCESS (process);
1142 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
1143 }
1144
1145 DEFUN ("set-process-query-on-exit-flag",
1146 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1147 2, 2, 0,
1148 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1149 If the second argument FLAG is non-nil, Emacs will query the user before
1150 exiting or killing a buffer if PROCESS is running. */)
1151 (process, flag)
1152 register Lisp_Object process, flag;
1153 {
1154 CHECK_PROCESS (process);
1155 XPROCESS (process)->kill_without_query = NILP (flag);
1156 return flag;
1157 }
1158
1159 DEFUN ("process-query-on-exit-flag",
1160 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1161 1, 1, 0,
1162 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1163 (process)
1164 register Lisp_Object process;
1165 {
1166 CHECK_PROCESS (process);
1167 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1168 }
1169
1170 #ifdef DATAGRAM_SOCKETS
1171 Lisp_Object Fprocess_datagram_address ();
1172 #endif
1173
1174 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1175 1, 2, 0,
1176 doc: /* Return the contact info of PROCESS; t for a real child.
1177 For a network or serial connection, the value depends on the optional
1178 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1179 SERVICE) for a network connection or (PORT SPEED) for a serial
1180 connection. If KEY is t, the complete contact information for the
1181 connection is returned, else the specific value for the keyword KEY is
1182 returned. See `make-network-process' or `make-serial-process' for a
1183 list of keywords. */)
1184 (process, key)
1185 register Lisp_Object process, key;
1186 {
1187 Lisp_Object contact;
1188
1189 CHECK_PROCESS (process);
1190 contact = XPROCESS (process)->childp;
1191
1192 #ifdef DATAGRAM_SOCKETS
1193 if (DATAGRAM_CONN_P (process)
1194 && (EQ (key, Qt) || EQ (key, QCremote)))
1195 contact = Fplist_put (contact, QCremote,
1196 Fprocess_datagram_address (process));
1197 #endif
1198
1199 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1200 return contact;
1201 if (NILP (key) && NETCONN_P (process))
1202 return Fcons (Fplist_get (contact, QChost),
1203 Fcons (Fplist_get (contact, QCservice), Qnil));
1204 if (NILP (key) && SERIALCONN_P (process))
1205 return Fcons (Fplist_get (contact, QCport),
1206 Fcons (Fplist_get (contact, QCspeed), Qnil));
1207 return Fplist_get (contact, key);
1208 }
1209
1210 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1211 1, 1, 0,
1212 doc: /* Return the plist of PROCESS. */)
1213 (process)
1214 register Lisp_Object process;
1215 {
1216 CHECK_PROCESS (process);
1217 return XPROCESS (process)->plist;
1218 }
1219
1220 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1221 2, 2, 0,
1222 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1223 (process, plist)
1224 register Lisp_Object process, plist;
1225 {
1226 CHECK_PROCESS (process);
1227 CHECK_LIST (plist);
1228
1229 XPROCESS (process)->plist = plist;
1230 return plist;
1231 }
1232
1233 #if 0 /* Turned off because we don't currently record this info
1234 in the process. Perhaps add it. */
1235 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1236 doc: /* Return the connection type of PROCESS.
1237 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1238 a socket connection. */)
1239 (process)
1240 Lisp_Object process;
1241 {
1242 return XPROCESS (process)->type;
1243 }
1244 #endif
1245
1246 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1247 doc: /* Return the connection type of PROCESS.
1248 The value is either the symbol `real', `network', or `serial'.
1249 PROCESS may be a process, a buffer, the name of a process or buffer, or
1250 nil, indicating the current buffer's process. */)
1251 (process)
1252 Lisp_Object process;
1253 {
1254 Lisp_Object proc;
1255 proc = get_process (process);
1256 return XPROCESS (proc)->type;
1257 }
1258
1259 #ifdef HAVE_SOCKETS
1260 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1261 1, 2, 0,
1262 doc: /* Convert network ADDRESS from internal format to a string.
1263 A 4 or 5 element vector represents an IPv4 address (with port number).
1264 An 8 or 9 element vector represents an IPv6 address (with port number).
1265 If optional second argument OMIT-PORT is non-nil, don't include a port
1266 number in the string, even when present in ADDRESS.
1267 Returns nil if format of ADDRESS is invalid. */)
1268 (address, omit_port)
1269 Lisp_Object address, omit_port;
1270 {
1271 if (NILP (address))
1272 return Qnil;
1273
1274 if (STRINGP (address)) /* AF_LOCAL */
1275 return address;
1276
1277 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1278 {
1279 register struct Lisp_Vector *p = XVECTOR (address);
1280 Lisp_Object args[10];
1281 int nargs, i;
1282
1283 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1284 {
1285 args[0] = build_string ("%d.%d.%d.%d");
1286 nargs = 4;
1287 }
1288 else if (p->size == 5)
1289 {
1290 args[0] = build_string ("%d.%d.%d.%d:%d");
1291 nargs = 5;
1292 }
1293 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1294 {
1295 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1296 nargs = 8;
1297 }
1298 else if (p->size == 9)
1299 {
1300 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1301 nargs = 9;
1302 }
1303 else
1304 return Qnil;
1305
1306 for (i = 0; i < nargs; i++)
1307 {
1308 EMACS_INT element = XINT (p->contents[i]);
1309
1310 if (element < 0 || element > 65535)
1311 return Qnil;
1312
1313 if (nargs <= 5 /* IPv4 */
1314 && i < 4 /* host, not port */
1315 && element > 255)
1316 return Qnil;
1317
1318 args[i+1] = p->contents[i];
1319 }
1320
1321 return Fformat (nargs+1, args);
1322 }
1323
1324 if (CONSP (address))
1325 {
1326 Lisp_Object args[2];
1327 args[0] = build_string ("<Family %d>");
1328 args[1] = Fcar (address);
1329 return Fformat (2, args);
1330 }
1331
1332 return Qnil;
1333 }
1334 #endif
1335 \f
1336 static Lisp_Object
1337 list_processes_1 (query_only)
1338 Lisp_Object query_only;
1339 {
1340 register Lisp_Object tail, tem;
1341 Lisp_Object proc, minspace, tem1;
1342 register struct Lisp_Process *p;
1343 char tembuf[300];
1344 int w_proc, w_buffer, w_tty;
1345 int exited = 0;
1346 Lisp_Object i_status, i_buffer, i_tty, i_command;
1347
1348 w_proc = 4; /* Proc */
1349 w_buffer = 6; /* Buffer */
1350 w_tty = 0; /* Omit if no ttys */
1351
1352 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1353 {
1354 int i;
1355
1356 proc = Fcdr (XCAR (tail));
1357 p = XPROCESS (proc);
1358 if (NILP (p->type))
1359 continue;
1360 if (!NILP (query_only) && p->kill_without_query)
1361 continue;
1362 if (STRINGP (p->name)
1363 && ( i = SCHARS (p->name), (i > w_proc)))
1364 w_proc = i;
1365 if (!NILP (p->buffer))
1366 {
1367 if (NILP (XBUFFER (p->buffer)->name))
1368 {
1369 if (w_buffer < 8)
1370 w_buffer = 8; /* (Killed) */
1371 }
1372 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1373 w_buffer = i;
1374 }
1375 if (STRINGP (p->tty_name)
1376 && (i = SCHARS (p->tty_name), (i > w_tty)))
1377 w_tty = i;
1378 }
1379
1380 XSETFASTINT (i_status, w_proc + 1);
1381 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1382 if (w_tty)
1383 {
1384 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1385 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1386 }
1387 else
1388 {
1389 i_tty = Qnil;
1390 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1391 }
1392
1393 XSETFASTINT (minspace, 1);
1394
1395 set_buffer_internal (XBUFFER (Vstandard_output));
1396 current_buffer->undo_list = Qt;
1397
1398 current_buffer->truncate_lines = Qt;
1399
1400 write_string ("Proc", -1);
1401 Findent_to (i_status, minspace); write_string ("Status", -1);
1402 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1403 if (!NILP (i_tty))
1404 {
1405 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1406 }
1407 Findent_to (i_command, minspace); write_string ("Command", -1);
1408 write_string ("\n", -1);
1409
1410 write_string ("----", -1);
1411 Findent_to (i_status, minspace); write_string ("------", -1);
1412 Findent_to (i_buffer, minspace); write_string ("------", -1);
1413 if (!NILP (i_tty))
1414 {
1415 Findent_to (i_tty, minspace); write_string ("---", -1);
1416 }
1417 Findent_to (i_command, minspace); write_string ("-------", -1);
1418 write_string ("\n", -1);
1419
1420 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1421 {
1422 Lisp_Object symbol;
1423
1424 proc = Fcdr (XCAR (tail));
1425 p = XPROCESS (proc);
1426 if (NILP (p->type))
1427 continue;
1428 if (!NILP (query_only) && p->kill_without_query)
1429 continue;
1430
1431 Finsert (1, &p->name);
1432 Findent_to (i_status, minspace);
1433
1434 if (p->raw_status_new)
1435 update_status (p);
1436 symbol = p->status;
1437 if (CONSP (p->status))
1438 symbol = XCAR (p->status);
1439
1440 if (EQ (symbol, Qsignal))
1441 {
1442 Lisp_Object tem;
1443 tem = Fcar (Fcdr (p->status));
1444 Fprinc (symbol, Qnil);
1445 }
1446 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1447 {
1448 if (EQ (symbol, Qexit))
1449 write_string ("closed", -1);
1450 else if (EQ (p->command, Qt))
1451 write_string ("stopped", -1);
1452 else if (EQ (symbol, Qrun))
1453 write_string ("open", -1);
1454 else
1455 Fprinc (symbol, Qnil);
1456 }
1457 else if (SERIALCONN1_P (p))
1458 {
1459 write_string ("running", -1);
1460 }
1461 else
1462 Fprinc (symbol, Qnil);
1463
1464 if (EQ (symbol, Qexit))
1465 {
1466 Lisp_Object tem;
1467 tem = Fcar (Fcdr (p->status));
1468 if (XFASTINT (tem))
1469 {
1470 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1471 write_string (tembuf, -1);
1472 }
1473 }
1474
1475 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1476 exited++;
1477
1478 Findent_to (i_buffer, minspace);
1479 if (NILP (p->buffer))
1480 insert_string ("(none)");
1481 else if (NILP (XBUFFER (p->buffer)->name))
1482 insert_string ("(Killed)");
1483 else
1484 Finsert (1, &XBUFFER (p->buffer)->name);
1485
1486 if (!NILP (i_tty))
1487 {
1488 Findent_to (i_tty, minspace);
1489 if (STRINGP (p->tty_name))
1490 Finsert (1, &p->tty_name);
1491 }
1492
1493 Findent_to (i_command, minspace);
1494
1495 if (EQ (p->status, Qlisten))
1496 {
1497 Lisp_Object port = Fplist_get (p->childp, QCservice);
1498 if (INTEGERP (port))
1499 port = Fnumber_to_string (port);
1500 if (NILP (port))
1501 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1502 sprintf (tembuf, "(network %s server on %s)\n",
1503 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1504 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1505 insert_string (tembuf);
1506 }
1507 else if (NETCONN1_P (p))
1508 {
1509 /* For a local socket, there is no host name,
1510 so display service instead. */
1511 Lisp_Object host = Fplist_get (p->childp, QChost);
1512 if (!STRINGP (host))
1513 {
1514 host = Fplist_get (p->childp, QCservice);
1515 if (INTEGERP (host))
1516 host = Fnumber_to_string (host);
1517 }
1518 if (NILP (host))
1519 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1520 sprintf (tembuf, "(network %s connection to %s)\n",
1521 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1522 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1523 insert_string (tembuf);
1524 }
1525 else if (SERIALCONN1_P (p))
1526 {
1527 Lisp_Object port = Fplist_get (p->childp, QCport);
1528 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1529 insert_string ("(serial port ");
1530 if (STRINGP (port))
1531 insert_string (SDATA (port));
1532 else
1533 insert_string ("?");
1534 if (INTEGERP (speed))
1535 {
1536 sprintf (tembuf, " at %ld b/s", (long) XINT (speed));
1537 insert_string (tembuf);
1538 }
1539 insert_string (")\n");
1540 }
1541 else
1542 {
1543 tem = p->command;
1544 while (1)
1545 {
1546 tem1 = Fcar (tem);
1547 if (NILP (tem1))
1548 break;
1549 Finsert (1, &tem1);
1550 tem = Fcdr (tem);
1551 if (NILP (tem))
1552 break;
1553 insert_string (" ");
1554 }
1555 insert_string ("\n");
1556 }
1557 }
1558 if (exited)
1559 {
1560 status_notify (NULL);
1561 redisplay_preserve_echo_area (13);
1562 }
1563 return Qnil;
1564 }
1565
1566 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1567 doc: /* Display a list of all processes.
1568 If optional argument QUERY-ONLY is non-nil, only processes with
1569 the query-on-exit flag set will be listed.
1570 Any process listed as exited or signaled is actually eliminated
1571 after the listing is made. */)
1572 (query_only)
1573 Lisp_Object query_only;
1574 {
1575 internal_with_output_to_temp_buffer ("*Process List*",
1576 list_processes_1, query_only);
1577 return Qnil;
1578 }
1579
1580 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1581 doc: /* Return a list of all processes. */)
1582 ()
1583 {
1584 return Fmapcar (Qcdr, Vprocess_alist);
1585 }
1586 \f
1587 /* Starting asynchronous inferior processes. */
1588
1589 static Lisp_Object start_process_unwind ();
1590
1591 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1592 doc: /* Start a program in a subprocess. Return the process object for it.
1593 NAME is name for process. It is modified if necessary to make it unique.
1594 BUFFER is the buffer (or buffer name) to associate with the process.
1595
1596 Process output (both standard output and standard error streams) goes
1597 at end of BUFFER, unless you specify an output stream or filter
1598 function to handle the output. BUFFER may also be nil, meaning that
1599 this process is not associated with any buffer.
1600
1601 PROGRAM is the program file name. It is searched for in PATH. If
1602 nil, just associate a pty with the buffer. Remaining arguments are
1603 strings to give program as arguments.
1604
1605 If you want to separate standard output from standard error, invoke
1606 the command through a shell and redirect one of them using the shell
1607 syntax.
1608
1609 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1610 (nargs, args)
1611 int nargs;
1612 register Lisp_Object *args;
1613 {
1614 Lisp_Object buffer, name, program, proc, current_dir, tem;
1615 register unsigned char **new_argv;
1616 register int i;
1617 int count = SPECPDL_INDEX ();
1618
1619 buffer = args[1];
1620 if (!NILP (buffer))
1621 buffer = Fget_buffer_create (buffer);
1622
1623 /* Make sure that the child will be able to chdir to the current
1624 buffer's current directory, or its unhandled equivalent. We
1625 can't just have the child check for an error when it does the
1626 chdir, since it's in a vfork.
1627
1628 We have to GCPRO around this because Fexpand_file_name and
1629 Funhandled_file_name_directory might call a file name handling
1630 function. The argument list is protected by the caller, so all
1631 we really have to worry about is buffer. */
1632 {
1633 struct gcpro gcpro1, gcpro2;
1634
1635 current_dir = current_buffer->directory;
1636
1637 GCPRO2 (buffer, current_dir);
1638
1639 current_dir = Funhandled_file_name_directory (current_dir);
1640 if (NILP (current_dir))
1641 /* If the file name handler says that current_dir is unreachable, use
1642 a sensible default. */
1643 current_dir = build_string ("~/");
1644 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1645 if (NILP (Ffile_accessible_directory_p (current_dir)))
1646 report_file_error ("Setting current directory",
1647 Fcons (current_buffer->directory, Qnil));
1648
1649 UNGCPRO;
1650 }
1651
1652 name = args[0];
1653 CHECK_STRING (name);
1654
1655 program = args[2];
1656
1657 if (!NILP (program))
1658 CHECK_STRING (program);
1659
1660 proc = make_process (name);
1661 /* If an error occurs and we can't start the process, we want to
1662 remove it from the process list. This means that each error
1663 check in create_process doesn't need to call remove_process
1664 itself; it's all taken care of here. */
1665 record_unwind_protect (start_process_unwind, proc);
1666
1667 XPROCESS (proc)->childp = Qt;
1668 XPROCESS (proc)->plist = Qnil;
1669 XPROCESS (proc)->type = Qreal;
1670 XPROCESS (proc)->buffer = buffer;
1671 XPROCESS (proc)->sentinel = Qnil;
1672 XPROCESS (proc)->filter = Qnil;
1673 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1674
1675 #ifdef ADAPTIVE_READ_BUFFERING
1676 XPROCESS (proc)->adaptive_read_buffering
1677 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1678 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1679 #endif
1680
1681 /* Make the process marker point into the process buffer (if any). */
1682 if (BUFFERP (buffer))
1683 set_marker_both (XPROCESS (proc)->mark, buffer,
1684 BUF_ZV (XBUFFER (buffer)),
1685 BUF_ZV_BYTE (XBUFFER (buffer)));
1686
1687 {
1688 /* Decide coding systems for communicating with the process. Here
1689 we don't setup the structure coding_system nor pay attention to
1690 unibyte mode. They are done in create_process. */
1691
1692 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1693 Lisp_Object coding_systems = Qt;
1694 Lisp_Object val, *args2;
1695 struct gcpro gcpro1, gcpro2;
1696
1697 val = Vcoding_system_for_read;
1698 if (NILP (val))
1699 {
1700 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1701 args2[0] = Qstart_process;
1702 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1703 GCPRO2 (proc, current_dir);
1704 if (!NILP (program))
1705 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1706 UNGCPRO;
1707 if (CONSP (coding_systems))
1708 val = XCAR (coding_systems);
1709 else if (CONSP (Vdefault_process_coding_system))
1710 val = XCAR (Vdefault_process_coding_system);
1711 }
1712 XPROCESS (proc)->decode_coding_system = val;
1713
1714 val = Vcoding_system_for_write;
1715 if (NILP (val))
1716 {
1717 if (EQ (coding_systems, Qt))
1718 {
1719 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1720 args2[0] = Qstart_process;
1721 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1722 GCPRO2 (proc, current_dir);
1723 if (!NILP (program))
1724 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1725 UNGCPRO;
1726 }
1727 if (CONSP (coding_systems))
1728 val = XCDR (coding_systems);
1729 else if (CONSP (Vdefault_process_coding_system))
1730 val = XCDR (Vdefault_process_coding_system);
1731 }
1732 XPROCESS (proc)->encode_coding_system = val;
1733 /* Note: At this momemnt, the above coding system may leave
1734 text-conversion or eol-conversion unspecified. They will be
1735 decided after we read output from the process and decode it by
1736 some coding system, or just before we actually send a text to
1737 the process. */
1738 }
1739
1740
1741 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1742 XPROCESS (proc)->decoding_carryover = 0;
1743 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1744
1745 XPROCESS (proc)->inherit_coding_system_flag
1746 = !(NILP (buffer) || !inherit_process_coding_system);
1747
1748 if (!NILP (program))
1749 {
1750 /* If program file name is not absolute, search our path for it.
1751 Put the name we will really use in TEM. */
1752 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1753 && !(SCHARS (program) > 1
1754 && IS_DEVICE_SEP (SREF (program, 1))))
1755 {
1756 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1757
1758 tem = Qnil;
1759 GCPRO4 (name, program, buffer, current_dir);
1760 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1761 UNGCPRO;
1762 if (NILP (tem))
1763 report_file_error ("Searching for program", Fcons (program, Qnil));
1764 tem = Fexpand_file_name (tem, Qnil);
1765 }
1766 else
1767 {
1768 if (!NILP (Ffile_directory_p (program)))
1769 error ("Specified program for new process is a directory");
1770 tem = program;
1771 }
1772
1773 /* If program file name starts with /: for quoting a magic name,
1774 discard that. */
1775 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1776 && SREF (tem, 1) == ':')
1777 tem = Fsubstring (tem, make_number (2), Qnil);
1778
1779 {
1780 Lisp_Object arg_encoding = Qnil;
1781 struct gcpro gcpro1;
1782 GCPRO1 (tem);
1783
1784 /* Encode the file name and put it in NEW_ARGV.
1785 That's where the child will use it to execute the program. */
1786 tem = Fcons (ENCODE_FILE (tem), Qnil);
1787
1788 /* Here we encode arguments by the coding system used for sending
1789 data to the process. We don't support using different coding
1790 systems for encoding arguments and for encoding data sent to the
1791 process. */
1792
1793 for (i = 3; i < nargs; i++)
1794 {
1795 tem = Fcons (args[i], tem);
1796 CHECK_STRING (XCAR (tem));
1797 if (STRING_MULTIBYTE (XCAR (tem)))
1798 {
1799 if (NILP (arg_encoding))
1800 arg_encoding = (complement_process_encoding_system
1801 (XPROCESS (proc)->encode_coding_system));
1802 XSETCAR (tem,
1803 code_convert_string_norecord
1804 (XCAR (tem), arg_encoding, 1));
1805 }
1806 }
1807
1808 UNGCPRO;
1809 }
1810
1811 /* Now that everything is encoded we can collect the strings into
1812 NEW_ARGV. */
1813 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1814 new_argv[nargs - 2] = 0;
1815
1816 for (i = nargs - 3; i >= 0; i--)
1817 {
1818 new_argv[i] = SDATA (XCAR (tem));
1819 tem = XCDR (tem);
1820 }
1821
1822 create_process (proc, (char **) new_argv, current_dir);
1823 }
1824 else
1825 create_pty (proc);
1826
1827 return unbind_to (count, proc);
1828 }
1829
1830 /* This function is the unwind_protect form for Fstart_process. If
1831 PROC doesn't have its pid set, then we know someone has signaled
1832 an error and the process wasn't started successfully, so we should
1833 remove it from the process list. */
1834 static Lisp_Object
1835 start_process_unwind (proc)
1836 Lisp_Object proc;
1837 {
1838 if (!PROCESSP (proc))
1839 abort ();
1840
1841 /* Was PROC started successfully? */
1842 if (XPROCESS (proc)->pid == -1)
1843 remove_process (proc);
1844
1845 return Qnil;
1846 }
1847
1848 static void
1849 create_process_1 (timer)
1850 struct atimer *timer;
1851 {
1852 /* Nothing to do. */
1853 }
1854
1855
1856 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1857 #ifdef USG
1858 #ifdef SIGCHLD
1859 /* Mimic blocking of signals on system V, which doesn't really have it. */
1860
1861 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1862 int sigchld_deferred;
1863
1864 SIGTYPE
1865 create_process_sigchld ()
1866 {
1867 signal (SIGCHLD, create_process_sigchld);
1868
1869 sigchld_deferred = 1;
1870 }
1871 #endif
1872 #endif
1873 #endif
1874
1875 void
1876 create_process (process, new_argv, current_dir)
1877 Lisp_Object process;
1878 char **new_argv;
1879 Lisp_Object current_dir;
1880 {
1881 int inchannel, outchannel;
1882 pid_t pid;
1883 int sv[2];
1884 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1885 int wait_child_setup[2];
1886 #endif
1887 #ifdef POSIX_SIGNALS
1888 sigset_t procmask;
1889 sigset_t blocked;
1890 struct sigaction sigint_action;
1891 struct sigaction sigquit_action;
1892 #ifdef AIX
1893 struct sigaction sighup_action;
1894 #endif
1895 #else /* !POSIX_SIGNALS */
1896 #if 0
1897 #ifdef SIGCHLD
1898 SIGTYPE (*sigchld)();
1899 #endif
1900 #endif /* 0 */
1901 #endif /* !POSIX_SIGNALS */
1902 /* Use volatile to protect variables from being clobbered by longjmp. */
1903 volatile int forkin, forkout;
1904 volatile int pty_flag = 0;
1905 #ifndef USE_CRT_DLL
1906 extern char **environ;
1907 #endif
1908
1909 inchannel = outchannel = -1;
1910
1911 #ifdef HAVE_PTYS
1912 if (!NILP (Vprocess_connection_type))
1913 outchannel = inchannel = allocate_pty ();
1914
1915 if (inchannel >= 0)
1916 {
1917 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1918 /* On most USG systems it does not work to open the pty's tty here,
1919 then close it and reopen it in the child. */
1920 #ifdef O_NOCTTY
1921 /* Don't let this terminal become our controlling terminal
1922 (in case we don't have one). */
1923 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1924 #else
1925 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1926 #endif
1927 if (forkin < 0)
1928 report_file_error ("Opening pty", Qnil);
1929 #else
1930 forkin = forkout = -1;
1931 #endif /* not USG, or USG_SUBTTY_WORKS */
1932 pty_flag = 1;
1933 }
1934 else
1935 #endif /* HAVE_PTYS */
1936 {
1937 int tem;
1938 tem = pipe (sv);
1939 if (tem < 0)
1940 report_file_error ("Creating pipe", Qnil);
1941 inchannel = sv[0];
1942 forkout = sv[1];
1943 tem = pipe (sv);
1944 if (tem < 0)
1945 {
1946 emacs_close (inchannel);
1947 emacs_close (forkout);
1948 report_file_error ("Creating pipe", Qnil);
1949 }
1950 outchannel = sv[1];
1951 forkin = sv[0];
1952 }
1953
1954 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1955 {
1956 int tem;
1957
1958 tem = pipe (wait_child_setup);
1959 if (tem < 0)
1960 report_file_error ("Creating pipe", Qnil);
1961 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1962 if (tem >= 0)
1963 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1964 if (tem < 0)
1965 {
1966 emacs_close (wait_child_setup[0]);
1967 emacs_close (wait_child_setup[1]);
1968 report_file_error ("Setting file descriptor flags", Qnil);
1969 }
1970 }
1971 #endif
1972
1973 #if 0
1974 /* Replaced by close_process_descs */
1975 set_exclusive_use (inchannel);
1976 set_exclusive_use (outchannel);
1977 #endif
1978
1979 #ifdef O_NONBLOCK
1980 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1981 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1982 #else
1983 #ifdef O_NDELAY
1984 fcntl (inchannel, F_SETFL, O_NDELAY);
1985 fcntl (outchannel, F_SETFL, O_NDELAY);
1986 #endif
1987 #endif
1988
1989 /* Record this as an active process, with its channels.
1990 As a result, child_setup will close Emacs's side of the pipes. */
1991 chan_process[inchannel] = process;
1992 XPROCESS (process)->infd = inchannel;
1993 XPROCESS (process)->outfd = outchannel;
1994
1995 /* Previously we recorded the tty descriptor used in the subprocess.
1996 It was only used for getting the foreground tty process, so now
1997 we just reopen the device (see emacs_get_tty_pgrp) as this is
1998 more portable (see USG_SUBTTY_WORKS above). */
1999
2000 XPROCESS (process)->pty_flag = pty_flag;
2001 XPROCESS (process)->status = Qrun;
2002 setup_process_coding_systems (process);
2003
2004 /* Delay interrupts until we have a chance to store
2005 the new fork's pid in its process structure */
2006 #ifdef POSIX_SIGNALS
2007 sigemptyset (&blocked);
2008 #ifdef SIGCHLD
2009 sigaddset (&blocked, SIGCHLD);
2010 #endif
2011 #ifdef HAVE_WORKING_VFORK
2012 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
2013 this sets the parent's signal handlers as well as the child's.
2014 So delay all interrupts whose handlers the child might munge,
2015 and record the current handlers so they can be restored later. */
2016 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
2017 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
2018 #ifdef AIX
2019 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
2020 #endif
2021 #endif /* HAVE_WORKING_VFORK */
2022 sigprocmask (SIG_BLOCK, &blocked, &procmask);
2023 #else /* !POSIX_SIGNALS */
2024 #ifdef SIGCHLD
2025 #if defined (BSD_SYSTEM) || defined (HPUX)
2026 sigsetmask (sigmask (SIGCHLD));
2027 #else /* ordinary USG */
2028 #if 0
2029 sigchld_deferred = 0;
2030 sigchld = signal (SIGCHLD, create_process_sigchld);
2031 #endif
2032 #endif /* ordinary USG */
2033 #endif /* SIGCHLD */
2034 #endif /* !POSIX_SIGNALS */
2035
2036 FD_SET (inchannel, &input_wait_mask);
2037 FD_SET (inchannel, &non_keyboard_wait_mask);
2038 if (inchannel > max_process_desc)
2039 max_process_desc = inchannel;
2040
2041 /* Until we store the proper pid, enable sigchld_handler
2042 to recognize an unknown pid as standing for this process.
2043 It is very important not to let this `marker' value stay
2044 in the table after this function has returned; if it does
2045 it might cause call-process to hang and subsequent asynchronous
2046 processes to get their return values scrambled. */
2047 XPROCESS (process)->pid = -1;
2048
2049 BLOCK_INPUT;
2050
2051 {
2052 /* child_setup must clobber environ on systems with true vfork.
2053 Protect it from permanent change. */
2054 char **save_environ = environ;
2055
2056 current_dir = ENCODE_FILE (current_dir);
2057
2058 #ifndef WINDOWSNT
2059 pid = vfork ();
2060 if (pid == 0)
2061 #endif /* not WINDOWSNT */
2062 {
2063 int xforkin = forkin;
2064 int xforkout = forkout;
2065
2066 #if 0 /* This was probably a mistake--it duplicates code later on,
2067 but fails to handle all the cases. */
2068 /* Make sure SIGCHLD is not blocked in the child. */
2069 sigsetmask (SIGEMPTYMASK);
2070 #endif
2071
2072 /* Make the pty be the controlling terminal of the process. */
2073 #ifdef HAVE_PTYS
2074 /* First, disconnect its current controlling terminal. */
2075 #ifdef HAVE_SETSID
2076 /* We tried doing setsid only if pty_flag, but it caused
2077 process_set_signal to fail on SGI when using a pipe. */
2078 setsid ();
2079 /* Make the pty's terminal the controlling terminal. */
2080 if (pty_flag)
2081 {
2082 #ifdef TIOCSCTTY
2083 /* We ignore the return value
2084 because faith@cs.unc.edu says that is necessary on Linux. */
2085 ioctl (xforkin, TIOCSCTTY, 0);
2086 #endif
2087 }
2088 #else /* not HAVE_SETSID */
2089 #ifdef USG
2090 /* It's very important to call setpgrp here and no time
2091 afterwards. Otherwise, we lose our controlling tty which
2092 is set when we open the pty. */
2093 setpgrp ();
2094 #endif /* USG */
2095 #endif /* not HAVE_SETSID */
2096 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2097 if (pty_flag && xforkin >= 0)
2098 {
2099 struct termios t;
2100 tcgetattr (xforkin, &t);
2101 t.c_lflag = LDISC1;
2102 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2103 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2104 }
2105 #else
2106 #if defined (NTTYDISC) && defined (TIOCSETD)
2107 if (pty_flag && xforkin >= 0)
2108 {
2109 /* Use new line discipline. */
2110 int ldisc = NTTYDISC;
2111 ioctl (xforkin, TIOCSETD, &ldisc);
2112 }
2113 #endif
2114 #endif
2115 #ifdef TIOCNOTTY
2116 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2117 can do TIOCSPGRP only to the process's controlling tty. */
2118 if (pty_flag)
2119 {
2120 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2121 I can't test it since I don't have 4.3. */
2122 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2123 ioctl (j, TIOCNOTTY, 0);
2124 emacs_close (j);
2125 #ifndef USG
2126 /* In order to get a controlling terminal on some versions
2127 of BSD, it is necessary to put the process in pgrp 0
2128 before it opens the terminal. */
2129 #ifdef HAVE_SETPGID
2130 setpgid (0, 0);
2131 #else
2132 setpgrp (0, 0);
2133 #endif
2134 #endif
2135 }
2136 #endif /* TIOCNOTTY */
2137
2138 #if !defined (DONT_REOPEN_PTY)
2139 /*** There is a suggestion that this ought to be a
2140 conditional on TIOCSPGRP,
2141 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2142 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2143 that system does seem to need this code, even though
2144 both HAVE_SETSID and TIOCSCTTY are defined. */
2145 /* Now close the pty (if we had it open) and reopen it.
2146 This makes the pty the controlling terminal of the subprocess. */
2147 if (pty_flag)
2148 {
2149
2150 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2151 would work? */
2152 if (xforkin >= 0)
2153 emacs_close (xforkin);
2154 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2155
2156 if (xforkin < 0)
2157 {
2158 emacs_write (1, "Couldn't open the pty terminal ", 31);
2159 emacs_write (1, pty_name, strlen (pty_name));
2160 emacs_write (1, "\n", 1);
2161 _exit (1);
2162 }
2163
2164 }
2165 #endif /* not DONT_REOPEN_PTY */
2166
2167 #ifdef SETUP_SLAVE_PTY
2168 if (pty_flag)
2169 {
2170 SETUP_SLAVE_PTY;
2171 }
2172 #endif /* SETUP_SLAVE_PTY */
2173 #ifdef AIX
2174 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2175 Now reenable it in the child, so it will die when we want it to. */
2176 if (pty_flag)
2177 signal (SIGHUP, SIG_DFL);
2178 #endif
2179 #endif /* HAVE_PTYS */
2180
2181 signal (SIGINT, SIG_DFL);
2182 signal (SIGQUIT, SIG_DFL);
2183
2184 /* Stop blocking signals in the child. */
2185 #ifdef POSIX_SIGNALS
2186 sigprocmask (SIG_SETMASK, &procmask, 0);
2187 #else /* !POSIX_SIGNALS */
2188 #ifdef SIGCHLD
2189 #if defined (BSD_SYSTEM) || defined (HPUX)
2190 sigsetmask (SIGEMPTYMASK);
2191 #else /* ordinary USG */
2192 #if 0
2193 signal (SIGCHLD, sigchld);
2194 #endif
2195 #endif /* ordinary USG */
2196 #endif /* SIGCHLD */
2197 #endif /* !POSIX_SIGNALS */
2198
2199 if (pty_flag)
2200 child_setup_tty (xforkout);
2201 #ifdef WINDOWSNT
2202 pid = child_setup (xforkin, xforkout, xforkout,
2203 new_argv, 1, current_dir);
2204 #else /* not WINDOWSNT */
2205 #ifdef FD_CLOEXEC
2206 emacs_close (wait_child_setup[0]);
2207 #endif
2208 child_setup (xforkin, xforkout, xforkout,
2209 new_argv, 1, current_dir);
2210 #endif /* not WINDOWSNT */
2211 }
2212 environ = save_environ;
2213 }
2214
2215 UNBLOCK_INPUT;
2216
2217 /* This runs in the Emacs process. */
2218 if (pid < 0)
2219 {
2220 if (forkin >= 0)
2221 emacs_close (forkin);
2222 if (forkin != forkout && forkout >= 0)
2223 emacs_close (forkout);
2224 }
2225 else
2226 {
2227 /* vfork succeeded. */
2228 XPROCESS (process)->pid = pid;
2229
2230 #ifdef WINDOWSNT
2231 register_child (pid, inchannel);
2232 #endif /* WINDOWSNT */
2233
2234 /* If the subfork execv fails, and it exits,
2235 this close hangs. I don't know why.
2236 So have an interrupt jar it loose. */
2237 {
2238 struct atimer *timer;
2239 EMACS_TIME offset;
2240
2241 stop_polling ();
2242 EMACS_SET_SECS_USECS (offset, 1, 0);
2243 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2244
2245 if (forkin >= 0)
2246 emacs_close (forkin);
2247
2248 cancel_atimer (timer);
2249 start_polling ();
2250 }
2251
2252 if (forkin != forkout && forkout >= 0)
2253 emacs_close (forkout);
2254
2255 #ifdef HAVE_PTYS
2256 if (pty_flag)
2257 XPROCESS (process)->tty_name = build_string (pty_name);
2258 else
2259 #endif
2260 XPROCESS (process)->tty_name = Qnil;
2261
2262 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2263 /* Wait for child_setup to complete in case that vfork is
2264 actually defined as fork. The descriptor wait_child_setup[1]
2265 of a pipe is closed at the child side either by close-on-exec
2266 on successful execvp or the _exit call in child_setup. */
2267 {
2268 char dummy;
2269
2270 emacs_close (wait_child_setup[1]);
2271 emacs_read (wait_child_setup[0], &dummy, 1);
2272 emacs_close (wait_child_setup[0]);
2273 }
2274 #endif
2275 }
2276
2277 /* Restore the signal state whether vfork succeeded or not.
2278 (We will signal an error, below, if it failed.) */
2279 #ifdef POSIX_SIGNALS
2280 #ifdef HAVE_WORKING_VFORK
2281 /* Restore the parent's signal handlers. */
2282 sigaction (SIGINT, &sigint_action, 0);
2283 sigaction (SIGQUIT, &sigquit_action, 0);
2284 #ifdef AIX
2285 sigaction (SIGHUP, &sighup_action, 0);
2286 #endif
2287 #endif /* HAVE_WORKING_VFORK */
2288 /* Stop blocking signals in the parent. */
2289 sigprocmask (SIG_SETMASK, &procmask, 0);
2290 #else /* !POSIX_SIGNALS */
2291 #ifdef SIGCHLD
2292 #if defined (BSD_SYSTEM) || defined (HPUX)
2293 sigsetmask (SIGEMPTYMASK);
2294 #else /* ordinary USG */
2295 #if 0
2296 signal (SIGCHLD, sigchld);
2297 /* Now really handle any of these signals
2298 that came in during this function. */
2299 if (sigchld_deferred)
2300 kill (getpid (), SIGCHLD);
2301 #endif
2302 #endif /* ordinary USG */
2303 #endif /* SIGCHLD */
2304 #endif /* !POSIX_SIGNALS */
2305
2306 /* Now generate the error if vfork failed. */
2307 if (pid < 0)
2308 report_file_error ("Doing vfork", Qnil);
2309 }
2310
2311 void
2312 create_pty (process)
2313 Lisp_Object process;
2314 {
2315 int inchannel, outchannel;
2316
2317 /* Use volatile to protect variables from being clobbered by longjmp. */
2318 volatile int forkin, forkout;
2319 volatile int pty_flag = 0;
2320
2321 inchannel = outchannel = -1;
2322
2323 #ifdef HAVE_PTYS
2324 if (!NILP (Vprocess_connection_type))
2325 outchannel = inchannel = allocate_pty ();
2326
2327 if (inchannel >= 0)
2328 {
2329 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
2330 /* On most USG systems it does not work to open the pty's tty here,
2331 then close it and reopen it in the child. */
2332 #ifdef O_NOCTTY
2333 /* Don't let this terminal become our controlling terminal
2334 (in case we don't have one). */
2335 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
2336 #else
2337 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
2338 #endif
2339 if (forkin < 0)
2340 report_file_error ("Opening pty", Qnil);
2341 #if defined (DONT_REOPEN_PTY)
2342 /* In the case that vfork is defined as fork, the parent process
2343 (Emacs) may send some data before the child process completes
2344 tty options setup. So we setup tty before forking. */
2345 child_setup_tty (forkout);
2346 #endif /* DONT_REOPEN_PTY */
2347 #else
2348 forkin = forkout = -1;
2349 #endif /* not USG, or USG_SUBTTY_WORKS */
2350 pty_flag = 1;
2351 }
2352 #endif /* HAVE_PTYS */
2353
2354 #ifdef O_NONBLOCK
2355 fcntl (inchannel, F_SETFL, O_NONBLOCK);
2356 fcntl (outchannel, F_SETFL, O_NONBLOCK);
2357 #else
2358 #ifdef O_NDELAY
2359 fcntl (inchannel, F_SETFL, O_NDELAY);
2360 fcntl (outchannel, F_SETFL, O_NDELAY);
2361 #endif
2362 #endif
2363
2364 /* Record this as an active process, with its channels.
2365 As a result, child_setup will close Emacs's side of the pipes. */
2366 chan_process[inchannel] = process;
2367 XPROCESS (process)->infd = inchannel;
2368 XPROCESS (process)->outfd = outchannel;
2369
2370 /* Previously we recorded the tty descriptor used in the subprocess.
2371 It was only used for getting the foreground tty process, so now
2372 we just reopen the device (see emacs_get_tty_pgrp) as this is
2373 more portable (see USG_SUBTTY_WORKS above). */
2374
2375 XPROCESS (process)->pty_flag = pty_flag;
2376 XPROCESS (process)->status = Qrun;
2377 setup_process_coding_systems (process);
2378
2379 FD_SET (inchannel, &input_wait_mask);
2380 FD_SET (inchannel, &non_keyboard_wait_mask);
2381 if (inchannel > max_process_desc)
2382 max_process_desc = inchannel;
2383
2384 XPROCESS (process)->pid = -2;
2385 #ifdef HAVE_PTYS
2386 if (pty_flag)
2387 XPROCESS (process)->tty_name = build_string (pty_name);
2388 else
2389 #endif
2390 XPROCESS (process)->tty_name = Qnil;
2391 }
2392
2393 \f
2394 #ifdef HAVE_SOCKETS
2395
2396 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2397 The address family of sa is not included in the result. */
2398
2399 static Lisp_Object
2400 conv_sockaddr_to_lisp (sa, len)
2401 struct sockaddr *sa;
2402 int len;
2403 {
2404 Lisp_Object address;
2405 int i;
2406 unsigned char *cp;
2407 register struct Lisp_Vector *p;
2408
2409 /* Workaround for a bug in getsockname on BSD: Names bound to
2410 sockets in the UNIX domain are inaccessible; getsockname returns
2411 a zero length name. */
2412 if (len < OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2413 return empty_unibyte_string;
2414
2415 switch (sa->sa_family)
2416 {
2417 case AF_INET:
2418 {
2419 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2420 len = sizeof (sin->sin_addr) + 1;
2421 address = Fmake_vector (make_number (len), Qnil);
2422 p = XVECTOR (address);
2423 p->contents[--len] = make_number (ntohs (sin->sin_port));
2424 cp = (unsigned char *) &sin->sin_addr;
2425 break;
2426 }
2427 #ifdef AF_INET6
2428 case AF_INET6:
2429 {
2430 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2431 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2432 len = sizeof (sin6->sin6_addr)/2 + 1;
2433 address = Fmake_vector (make_number (len), Qnil);
2434 p = XVECTOR (address);
2435 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2436 for (i = 0; i < len; i++)
2437 p->contents[i] = make_number (ntohs (ip6[i]));
2438 return address;
2439 }
2440 #endif
2441 #ifdef HAVE_LOCAL_SOCKETS
2442 case AF_LOCAL:
2443 {
2444 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2445 for (i = 0; i < sizeof (sockun->sun_path); i++)
2446 if (sockun->sun_path[i] == 0)
2447 break;
2448 return make_unibyte_string (sockun->sun_path, i);
2449 }
2450 #endif
2451 default:
2452 len -= OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2453 address = Fcons (make_number (sa->sa_family),
2454 Fmake_vector (make_number (len), Qnil));
2455 p = XVECTOR (XCDR (address));
2456 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2457 break;
2458 }
2459
2460 i = 0;
2461 while (i < len)
2462 p->contents[i++] = make_number (*cp++);
2463
2464 return address;
2465 }
2466
2467
2468 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2469
2470 static int
2471 get_lisp_to_sockaddr_size (address, familyp)
2472 Lisp_Object address;
2473 int *familyp;
2474 {
2475 register struct Lisp_Vector *p;
2476
2477 if (VECTORP (address))
2478 {
2479 p = XVECTOR (address);
2480 if (p->size == 5)
2481 {
2482 *familyp = AF_INET;
2483 return sizeof (struct sockaddr_in);
2484 }
2485 #ifdef AF_INET6
2486 else if (p->size == 9)
2487 {
2488 *familyp = AF_INET6;
2489 return sizeof (struct sockaddr_in6);
2490 }
2491 #endif
2492 }
2493 #ifdef HAVE_LOCAL_SOCKETS
2494 else if (STRINGP (address))
2495 {
2496 *familyp = AF_LOCAL;
2497 return sizeof (struct sockaddr_un);
2498 }
2499 #endif
2500 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2501 {
2502 struct sockaddr *sa;
2503 *familyp = XINT (XCAR (address));
2504 p = XVECTOR (XCDR (address));
2505 return p->size + sizeof (sa->sa_family);
2506 }
2507 return 0;
2508 }
2509
2510 /* Convert an address object (vector or string) to an internal sockaddr.
2511
2512 The address format has been basically validated by
2513 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2514 it could have come from user data. So if FAMILY is not valid,
2515 we return after zeroing *SA. */
2516
2517 static void
2518 conv_lisp_to_sockaddr (family, address, sa, len)
2519 int family;
2520 Lisp_Object address;
2521 struct sockaddr *sa;
2522 int len;
2523 {
2524 register struct Lisp_Vector *p;
2525 register unsigned char *cp = NULL;
2526 register int i;
2527
2528 bzero (sa, len);
2529
2530 if (VECTORP (address))
2531 {
2532 p = XVECTOR (address);
2533 if (family == AF_INET)
2534 {
2535 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2536 len = sizeof (sin->sin_addr) + 1;
2537 i = XINT (p->contents[--len]);
2538 sin->sin_port = htons (i);
2539 cp = (unsigned char *)&sin->sin_addr;
2540 sa->sa_family = family;
2541 }
2542 #ifdef AF_INET6
2543 else if (family == AF_INET6)
2544 {
2545 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2546 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2547 len = sizeof (sin6->sin6_addr) + 1;
2548 i = XINT (p->contents[--len]);
2549 sin6->sin6_port = htons (i);
2550 for (i = 0; i < len; i++)
2551 if (INTEGERP (p->contents[i]))
2552 {
2553 int j = XFASTINT (p->contents[i]) & 0xffff;
2554 ip6[i] = ntohs (j);
2555 }
2556 sa->sa_family = family;
2557 return;
2558 }
2559 #endif
2560 else
2561 return;
2562 }
2563 else if (STRINGP (address))
2564 {
2565 #ifdef HAVE_LOCAL_SOCKETS
2566 if (family == AF_LOCAL)
2567 {
2568 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2569 cp = SDATA (address);
2570 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2571 sockun->sun_path[i] = *cp++;
2572 sa->sa_family = family;
2573 }
2574 #endif
2575 return;
2576 }
2577 else
2578 {
2579 p = XVECTOR (XCDR (address));
2580 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2581 }
2582
2583 for (i = 0; i < len; i++)
2584 if (INTEGERP (p->contents[i]))
2585 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2586 }
2587
2588 #ifdef DATAGRAM_SOCKETS
2589 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2590 1, 1, 0,
2591 doc: /* Get the current datagram address associated with PROCESS. */)
2592 (process)
2593 Lisp_Object process;
2594 {
2595 int channel;
2596
2597 CHECK_PROCESS (process);
2598
2599 if (!DATAGRAM_CONN_P (process))
2600 return Qnil;
2601
2602 channel = XPROCESS (process)->infd;
2603 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2604 datagram_address[channel].len);
2605 }
2606
2607 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2608 2, 2, 0,
2609 doc: /* Set the datagram address for PROCESS to ADDRESS.
2610 Returns nil upon error setting address, ADDRESS otherwise. */)
2611 (process, address)
2612 Lisp_Object process, address;
2613 {
2614 int channel;
2615 int family, len;
2616
2617 CHECK_PROCESS (process);
2618
2619 if (!DATAGRAM_CONN_P (process))
2620 return Qnil;
2621
2622 channel = XPROCESS (process)->infd;
2623
2624 len = get_lisp_to_sockaddr_size (address, &family);
2625 if (datagram_address[channel].len != len)
2626 return Qnil;
2627 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2628 return address;
2629 }
2630 #endif
2631 \f
2632
2633 static const struct socket_options {
2634 /* The name of this option. Should be lowercase version of option
2635 name without SO_ prefix. */
2636 char *name;
2637 /* Option level SOL_... */
2638 int optlevel;
2639 /* Option number SO_... */
2640 int optnum;
2641 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2642 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2643 } socket_options[] =
2644 {
2645 #ifdef SO_BINDTODEVICE
2646 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2647 #endif
2648 #ifdef SO_BROADCAST
2649 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2650 #endif
2651 #ifdef SO_DONTROUTE
2652 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2653 #endif
2654 #ifdef SO_KEEPALIVE
2655 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2656 #endif
2657 #ifdef SO_LINGER
2658 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2659 #endif
2660 #ifdef SO_OOBINLINE
2661 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2662 #endif
2663 #ifdef SO_PRIORITY
2664 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2665 #endif
2666 #ifdef SO_REUSEADDR
2667 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2668 #endif
2669 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2670 };
2671
2672 /* Set option OPT to value VAL on socket S.
2673
2674 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2675 Signals an error if setting a known option fails.
2676 */
2677
2678 static int
2679 set_socket_option (s, opt, val)
2680 int s;
2681 Lisp_Object opt, val;
2682 {
2683 char *name;
2684 const struct socket_options *sopt;
2685 int ret = 0;
2686
2687 CHECK_SYMBOL (opt);
2688
2689 name = (char *) SDATA (SYMBOL_NAME (opt));
2690 for (sopt = socket_options; sopt->name; sopt++)
2691 if (strcmp (name, sopt->name) == 0)
2692 break;
2693
2694 switch (sopt->opttype)
2695 {
2696 case SOPT_BOOL:
2697 {
2698 int optval;
2699 optval = NILP (val) ? 0 : 1;
2700 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2701 &optval, sizeof (optval));
2702 break;
2703 }
2704
2705 case SOPT_INT:
2706 {
2707 int optval;
2708 if (INTEGERP (val))
2709 optval = XINT (val);
2710 else
2711 error ("Bad option value for %s", name);
2712 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2713 &optval, sizeof (optval));
2714 break;
2715 }
2716
2717 #ifdef SO_BINDTODEVICE
2718 case SOPT_IFNAME:
2719 {
2720 char devname[IFNAMSIZ+1];
2721
2722 /* This is broken, at least in the Linux 2.4 kernel.
2723 To unbind, the arg must be a zero integer, not the empty string.
2724 This should work on all systems. KFS. 2003-09-23. */
2725 bzero (devname, sizeof devname);
2726 if (STRINGP (val))
2727 {
2728 char *arg = (char *) SDATA (val);
2729 int len = min (strlen (arg), IFNAMSIZ);
2730 bcopy (arg, devname, len);
2731 }
2732 else if (!NILP (val))
2733 error ("Bad option value for %s", name);
2734 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2735 devname, IFNAMSIZ);
2736 break;
2737 }
2738 #endif
2739
2740 #ifdef SO_LINGER
2741 case SOPT_LINGER:
2742 {
2743 struct linger linger;
2744
2745 linger.l_onoff = 1;
2746 linger.l_linger = 0;
2747 if (INTEGERP (val))
2748 linger.l_linger = XINT (val);
2749 else
2750 linger.l_onoff = NILP (val) ? 0 : 1;
2751 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2752 &linger, sizeof (linger));
2753 break;
2754 }
2755 #endif
2756
2757 default:
2758 return 0;
2759 }
2760
2761 if (ret < 0)
2762 report_file_error ("Cannot set network option",
2763 Fcons (opt, Fcons (val, Qnil)));
2764 return (1 << sopt->optbit);
2765 }
2766
2767
2768 DEFUN ("set-network-process-option",
2769 Fset_network_process_option, Sset_network_process_option,
2770 3, 4, 0,
2771 doc: /* For network process PROCESS set option OPTION to value VALUE.
2772 See `make-network-process' for a list of options and values.
2773 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2774 OPTION is not a supported option, return nil instead; otherwise return t. */)
2775 (process, option, value, no_error)
2776 Lisp_Object process, option, value;
2777 Lisp_Object no_error;
2778 {
2779 int s;
2780 struct Lisp_Process *p;
2781
2782 CHECK_PROCESS (process);
2783 p = XPROCESS (process);
2784 if (!NETCONN1_P (p))
2785 error ("Process is not a network process");
2786
2787 s = p->infd;
2788 if (s < 0)
2789 error ("Process is not running");
2790
2791 if (set_socket_option (s, option, value))
2792 {
2793 p->childp = Fplist_put (p->childp, option, value);
2794 return Qt;
2795 }
2796
2797 if (NILP (no_error))
2798 error ("Unknown or unsupported option");
2799
2800 return Qnil;
2801 }
2802
2803 \f
2804 #ifdef HAVE_SERIAL
2805 DEFUN ("serial-process-configure",
2806 Fserial_process_configure,
2807 Sserial_process_configure,
2808 0, MANY, 0,
2809 doc: /* Configure speed, bytesize, etc. of a serial process.
2810
2811 Arguments are specified as keyword/argument pairs. Attributes that
2812 are not given are re-initialized from the process's current
2813 configuration (available via the function `process-contact') or set to
2814 reasonable default values. The following arguments are defined:
2815
2816 :process PROCESS
2817 :name NAME
2818 :buffer BUFFER
2819 :port PORT
2820 -- Any of these arguments can be given to identify the process that is
2821 to be configured. If none of these arguments is given, the current
2822 buffer's process is used.
2823
2824 :speed SPEED -- SPEED is the speed of the serial port in bits per
2825 second, also called baud rate. Any value can be given for SPEED, but
2826 most serial ports work only at a few defined values between 1200 and
2827 115200, with 9600 being the most common value. If SPEED is nil, the
2828 serial port is not configured any further, i.e., all other arguments
2829 are ignored. This may be useful for special serial ports such as
2830 Bluetooth-to-serial converters which can only be configured through AT
2831 commands. A value of nil for SPEED can be used only when passed
2832 through `make-serial-process' or `serial-term'.
2833
2834 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2835 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2836
2837 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2838 `odd' (use odd parity), or the symbol `even' (use even parity). If
2839 PARITY is not given, no parity is used.
2840
2841 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2842 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2843 is not given or nil, 1 stopbit is used.
2844
2845 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2846 flowcontrol to be used, which is either nil (don't use flowcontrol),
2847 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2848 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2849 flowcontrol is used.
2850
2851 `serial-process-configure' is called by `make-serial-process' for the
2852 initial configuration of the serial port.
2853
2854 Examples:
2855
2856 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2857
2858 \(serial-process-configure
2859 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2860
2861 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2862
2863 usage: (serial-process-configure &rest ARGS) */)
2864 (nargs, args)
2865 int nargs;
2866 Lisp_Object *args;
2867 {
2868 struct Lisp_Process *p;
2869 Lisp_Object contact = Qnil;
2870 Lisp_Object proc = Qnil;
2871 struct gcpro gcpro1;
2872
2873 contact = Flist (nargs, args);
2874 GCPRO1 (contact);
2875
2876 proc = Fplist_get (contact, QCprocess);
2877 if (NILP (proc))
2878 proc = Fplist_get (contact, QCname);
2879 if (NILP (proc))
2880 proc = Fplist_get (contact, QCbuffer);
2881 if (NILP (proc))
2882 proc = Fplist_get (contact, QCport);
2883 proc = get_process (proc);
2884 p = XPROCESS (proc);
2885 if (!EQ (p->type, Qserial))
2886 error ("Not a serial process");
2887
2888 if (NILP (Fplist_get (p->childp, QCspeed)))
2889 {
2890 UNGCPRO;
2891 return Qnil;
2892 }
2893
2894 serial_configure (p, contact);
2895
2896 UNGCPRO;
2897 return Qnil;
2898 }
2899
2900 /* Used by make-serial-process to recover from errors. */
2901 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2902 {
2903 if (!PROCESSP (proc))
2904 abort ();
2905 remove_process (proc);
2906 return Qnil;
2907 }
2908
2909 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2910 0, MANY, 0,
2911 doc: /* Create and return a serial port process.
2912
2913 In Emacs, serial port connections are represented by process objects,
2914 so input and output work as for subprocesses, and `delete-process'
2915 closes a serial port connection. However, a serial process has no
2916 process id, it cannot be signaled, and the status codes are different
2917 from normal processes.
2918
2919 `make-serial-process' creates a process and a buffer, on which you
2920 probably want to use `process-send-string'. Try \\[serial-term] for
2921 an interactive terminal. See below for examples.
2922
2923 Arguments are specified as keyword/argument pairs. The following
2924 arguments are defined:
2925
2926 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2927 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2928 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2929 the backslashes in strings).
2930
2931 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2932 which is called by `make-serial-process'.
2933
2934 :name NAME -- NAME is the name of the process. If NAME is not given,
2935 the value of PORT is used.
2936
2937 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2938 with the process. Process output goes at the end of that buffer,
2939 unless you specify an output stream or filter function to handle the
2940 output. If BUFFER is not given, the value of NAME is used.
2941
2942 :coding CODING -- If CODING is a symbol, it specifies the coding
2943 system used for both reading and writing for this process. If CODING
2944 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2945 ENCODING is used for writing.
2946
2947 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2948 the process is running. If BOOL is not given, query before exiting.
2949
2950 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2951 In the stopped state, a serial process does not accept incoming data,
2952 but you can send outgoing data. The stopped state is cleared by
2953 `continue-process' and set by `stop-process'.
2954
2955 :filter FILTER -- Install FILTER as the process filter.
2956
2957 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2958
2959 :plist PLIST -- Install PLIST as the initial plist of the process.
2960
2961 :speed
2962 :bytesize
2963 :parity
2964 :stopbits
2965 :flowcontrol
2966 -- These arguments are handled by `serial-process-configure', which is
2967 called by `make-serial-process'.
2968
2969 The original argument list, possibly modified by later configuration,
2970 is available via the function `process-contact'.
2971
2972 Examples:
2973
2974 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2975
2976 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2977
2978 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2979
2980 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2981
2982 usage: (make-serial-process &rest ARGS) */)
2983 (nargs, args)
2984 int nargs;
2985 Lisp_Object *args;
2986 {
2987 int fd = -1;
2988 Lisp_Object proc, contact, port;
2989 struct Lisp_Process *p;
2990 struct gcpro gcpro1;
2991 Lisp_Object name, buffer;
2992 Lisp_Object tem, val;
2993 int specpdl_count = -1;
2994
2995 if (nargs == 0)
2996 return Qnil;
2997
2998 contact = Flist (nargs, args);
2999 GCPRO1 (contact);
3000
3001 port = Fplist_get (contact, QCport);
3002 if (NILP (port))
3003 error ("No port specified");
3004 CHECK_STRING (port);
3005
3006 if (NILP (Fplist_member (contact, QCspeed)))
3007 error (":speed not specified");
3008 if (!NILP (Fplist_get (contact, QCspeed)))
3009 CHECK_NUMBER (Fplist_get (contact, QCspeed));
3010
3011 name = Fplist_get (contact, QCname);
3012 if (NILP (name))
3013 name = port;
3014 CHECK_STRING (name);
3015 proc = make_process (name);
3016 specpdl_count = SPECPDL_INDEX ();
3017 record_unwind_protect (make_serial_process_unwind, proc);
3018 p = XPROCESS (proc);
3019
3020 fd = serial_open ((char*) SDATA (port));
3021 p->infd = fd;
3022 p->outfd = fd;
3023 if (fd > max_process_desc)
3024 max_process_desc = fd;
3025 chan_process[fd] = proc;
3026
3027 buffer = Fplist_get (contact, QCbuffer);
3028 if (NILP (buffer))
3029 buffer = name;
3030 buffer = Fget_buffer_create (buffer);
3031 p->buffer = buffer;
3032
3033 p->childp = contact;
3034 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3035 p->type = Qserial;
3036 p->sentinel = Fplist_get (contact, QCsentinel);
3037 p->filter = Fplist_get (contact, QCfilter);
3038 p->log = Qnil;
3039 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3040 p->kill_without_query = 1;
3041 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
3042 p->command = Qt;
3043 p->pty_flag = 0;
3044
3045 if (!EQ (p->command, Qt))
3046 {
3047 FD_SET (fd, &input_wait_mask);
3048 FD_SET (fd, &non_keyboard_wait_mask);
3049 }
3050
3051 if (BUFFERP (buffer))
3052 {
3053 set_marker_both (p->mark, buffer,
3054 BUF_ZV (XBUFFER (buffer)),
3055 BUF_ZV_BYTE (XBUFFER (buffer)));
3056 }
3057
3058 tem = Fplist_member (contact, QCcoding);
3059 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3060 tem = Qnil;
3061
3062 val = Qnil;
3063 if (!NILP (tem))
3064 {
3065 val = XCAR (XCDR (tem));
3066 if (CONSP (val))
3067 val = XCAR (val);
3068 }
3069 else if (!NILP (Vcoding_system_for_read))
3070 val = Vcoding_system_for_read;
3071 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3072 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3073 val = Qnil;
3074 p->decode_coding_system = val;
3075
3076 val = Qnil;
3077 if (!NILP (tem))
3078 {
3079 val = XCAR (XCDR (tem));
3080 if (CONSP (val))
3081 val = XCDR (val);
3082 }
3083 else if (!NILP (Vcoding_system_for_write))
3084 val = Vcoding_system_for_write;
3085 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3086 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3087 val = Qnil;
3088 p->encode_coding_system = val;
3089
3090 setup_process_coding_systems (proc);
3091 p->decoding_buf = make_uninit_string (0);
3092 p->decoding_carryover = 0;
3093 p->encoding_buf = make_uninit_string (0);
3094 p->inherit_coding_system_flag
3095 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3096
3097 Fserial_process_configure(nargs, args);
3098
3099 specpdl_ptr = specpdl + specpdl_count;
3100
3101 UNGCPRO;
3102 return proc;
3103 }
3104 #endif /* HAVE_SERIAL */
3105
3106 /* Create a network stream/datagram client/server process. Treated
3107 exactly like a normal process when reading and writing. Primary
3108 differences are in status display and process deletion. A network
3109 connection has no PID; you cannot signal it. All you can do is
3110 stop/continue it and deactivate/close it via delete-process */
3111
3112 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
3113 0, MANY, 0,
3114 doc: /* Create and return a network server or client process.
3115
3116 In Emacs, network connections are represented by process objects, so
3117 input and output work as for subprocesses and `delete-process' closes
3118 a network connection. However, a network process has no process id,
3119 it cannot be signaled, and the status codes are different from normal
3120 processes.
3121
3122 Arguments are specified as keyword/argument pairs. The following
3123 arguments are defined:
3124
3125 :name NAME -- NAME is name for process. It is modified if necessary
3126 to make it unique.
3127
3128 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3129 with the process. Process output goes at end of that buffer, unless
3130 you specify an output stream or filter function to handle the output.
3131 BUFFER may be also nil, meaning that this process is not associated
3132 with any buffer.
3133
3134 :host HOST -- HOST is name of the host to connect to, or its IP
3135 address. The symbol `local' specifies the local host. If specified
3136 for a server process, it must be a valid name or address for the local
3137 host, and only clients connecting to that address will be accepted.
3138
3139 :service SERVICE -- SERVICE is name of the service desired, or an
3140 integer specifying a port number to connect to. If SERVICE is t,
3141 a random port number is selected for the server. (If Emacs was
3142 compiled with getaddrinfo, a port number can also be specified as a
3143 string, e.g. "80", as well as an integer. This is not portable.)
3144
3145 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3146 stream type connection, `datagram' creates a datagram type connection,
3147 `seqpacket' creates a reliable datagram connection.
3148
3149 :family FAMILY -- FAMILY is the address (and protocol) family for the
3150 service specified by HOST and SERVICE. The default (nil) is to use
3151 whatever address family (IPv4 or IPv6) that is defined for the host
3152 and port number specified by HOST and SERVICE. Other address families
3153 supported are:
3154 local -- for a local (i.e. UNIX) address specified by SERVICE.
3155 ipv4 -- use IPv4 address family only.
3156 ipv6 -- use IPv6 address family only.
3157
3158 :local ADDRESS -- ADDRESS is the local address used for the connection.
3159 This parameter is ignored when opening a client process. When specified
3160 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3161
3162 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3163 connection. This parameter is ignored when opening a stream server
3164 process. For a datagram server process, it specifies the initial
3165 setting of the remote datagram address. When specified for a client
3166 process, the FAMILY, HOST, and SERVICE args are ignored.
3167
3168 The format of ADDRESS depends on the address family:
3169 - An IPv4 address is represented as an vector of integers [A B C D P]
3170 corresponding to numeric IP address A.B.C.D and port number P.
3171 - A local address is represented as a string with the address in the
3172 local address space.
3173 - An "unsupported family" address is represented by a cons (F . AV)
3174 where F is the family number and AV is a vector containing the socket
3175 address data with one element per address data byte. Do not rely on
3176 this format in portable code, as it may depend on implementation
3177 defined constants, data sizes, and data structure alignment.
3178
3179 :coding CODING -- If CODING is a symbol, it specifies the coding
3180 system used for both reading and writing for this process. If CODING
3181 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3182 ENCODING is used for writing.
3183
3184 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3185 return without waiting for the connection to complete; instead, the
3186 sentinel function will be called with second arg matching "open" (if
3187 successful) or "failed" when the connect completes. Default is to use
3188 a blocking connect (i.e. wait) for stream type connections.
3189
3190 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3191 running when Emacs is exited.
3192
3193 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3194 In the stopped state, a server process does not accept new
3195 connections, and a client process does not handle incoming traffic.
3196 The stopped state is cleared by `continue-process' and set by
3197 `stop-process'.
3198
3199 :filter FILTER -- Install FILTER as the process filter.
3200
3201 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3202 process filter are multibyte, otherwise they are unibyte.
3203 If this keyword is not specified, the strings are multibyte if
3204 `default-enable-multibyte-characters' is non-nil.
3205
3206 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3207
3208 :log LOG -- Install LOG as the server process log function. This
3209 function is called when the server accepts a network connection from a
3210 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3211 is the server process, CLIENT is the new process for the connection,
3212 and MESSAGE is a string.
3213
3214 :plist PLIST -- Install PLIST as the new process' initial plist.
3215
3216 :server QLEN -- if QLEN is non-nil, create a server process for the
3217 specified FAMILY, SERVICE, and connection type (stream or datagram).
3218 If QLEN is an integer, it is used as the max. length of the server's
3219 pending connection queue (also known as the backlog); the default
3220 queue length is 5. Default is to create a client process.
3221
3222 The following network options can be specified for this connection:
3223
3224 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3225 :dontroute BOOL -- Only send to directly connected hosts.
3226 :keepalive BOOL -- Send keep-alive messages on network stream.
3227 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3228 :oobinline BOOL -- Place out-of-band data in receive data stream.
3229 :priority INT -- Set protocol defined priority for sent packets.
3230 :reuseaddr BOOL -- Allow reusing a recently used local address
3231 (this is allowed by default for a server process).
3232 :bindtodevice NAME -- bind to interface NAME. Using this may require
3233 special privileges on some systems.
3234
3235 Consult the relevant system programmer's manual pages for more
3236 information on using these options.
3237
3238
3239 A server process will listen for and accept connections from clients.
3240 When a client connection is accepted, a new network process is created
3241 for the connection with the following parameters:
3242
3243 - The client's process name is constructed by concatenating the server
3244 process' NAME and a client identification string.
3245 - If the FILTER argument is non-nil, the client process will not get a
3246 separate process buffer; otherwise, the client's process buffer is a newly
3247 created buffer named after the server process' BUFFER name or process
3248 NAME concatenated with the client identification string.
3249 - The connection type and the process filter and sentinel parameters are
3250 inherited from the server process' TYPE, FILTER and SENTINEL.
3251 - The client process' contact info is set according to the client's
3252 addressing information (typically an IP address and a port number).
3253 - The client process' plist is initialized from the server's plist.
3254
3255 Notice that the FILTER and SENTINEL args are never used directly by
3256 the server process. Also, the BUFFER argument is not used directly by
3257 the server process, but via the optional :log function, accepted (and
3258 failed) connections may be logged in the server process' buffer.
3259
3260 The original argument list, modified with the actual connection
3261 information, is available via the `process-contact' function.
3262
3263 usage: (make-network-process &rest ARGS) */)
3264 (nargs, args)
3265 int nargs;
3266 Lisp_Object *args;
3267 {
3268 Lisp_Object proc;
3269 Lisp_Object contact;
3270 struct Lisp_Process *p;
3271 #ifdef HAVE_GETADDRINFO
3272 struct addrinfo ai, *res, *lres;
3273 struct addrinfo hints;
3274 char *portstring, portbuf[128];
3275 #else /* HAVE_GETADDRINFO */
3276 struct _emacs_addrinfo
3277 {
3278 int ai_family;
3279 int ai_socktype;
3280 int ai_protocol;
3281 int ai_addrlen;
3282 struct sockaddr *ai_addr;
3283 struct _emacs_addrinfo *ai_next;
3284 } ai, *res, *lres;
3285 #endif /* HAVE_GETADDRINFO */
3286 struct sockaddr_in address_in;
3287 #ifdef HAVE_LOCAL_SOCKETS
3288 struct sockaddr_un address_un;
3289 #endif
3290 int port;
3291 int ret = 0;
3292 int xerrno = 0;
3293 int s = -1, outch, inch;
3294 struct gcpro gcpro1;
3295 int count = SPECPDL_INDEX ();
3296 int count1;
3297 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3298 Lisp_Object tem;
3299 Lisp_Object name, buffer, host, service, address;
3300 Lisp_Object filter, sentinel;
3301 int is_non_blocking_client = 0;
3302 int is_server = 0, backlog = 5;
3303 int socktype;
3304 int family = -1;
3305
3306 if (nargs == 0)
3307 return Qnil;
3308
3309 /* Save arguments for process-contact and clone-process. */
3310 contact = Flist (nargs, args);
3311 GCPRO1 (contact);
3312
3313 #ifdef WINDOWSNT
3314 /* Ensure socket support is loaded if available. */
3315 init_winsock (TRUE);
3316 #endif
3317
3318 /* :type TYPE (nil: stream, datagram */
3319 tem = Fplist_get (contact, QCtype);
3320 if (NILP (tem))
3321 socktype = SOCK_STREAM;
3322 #ifdef DATAGRAM_SOCKETS
3323 else if (EQ (tem, Qdatagram))
3324 socktype = SOCK_DGRAM;
3325 #endif
3326 #ifdef HAVE_SEQPACKET
3327 else if (EQ (tem, Qseqpacket))
3328 socktype = SOCK_SEQPACKET;
3329 #endif
3330 else
3331 error ("Unsupported connection type");
3332
3333 /* :server BOOL */
3334 tem = Fplist_get (contact, QCserver);
3335 if (!NILP (tem))
3336 {
3337 /* Don't support network sockets when non-blocking mode is
3338 not available, since a blocked Emacs is not useful. */
3339 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3340 error ("Network servers not supported");
3341 #else
3342 is_server = 1;
3343 if (INTEGERP (tem))
3344 backlog = XINT (tem);
3345 #endif
3346 }
3347
3348 /* Make QCaddress an alias for :local (server) or :remote (client). */
3349 QCaddress = is_server ? QClocal : QCremote;
3350
3351 /* :nowait BOOL */
3352 if (!is_server && socktype != SOCK_DGRAM
3353 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3354 {
3355 #ifndef NON_BLOCKING_CONNECT
3356 error ("Non-blocking connect not supported");
3357 #else
3358 is_non_blocking_client = 1;
3359 #endif
3360 }
3361
3362 name = Fplist_get (contact, QCname);
3363 buffer = Fplist_get (contact, QCbuffer);
3364 filter = Fplist_get (contact, QCfilter);
3365 sentinel = Fplist_get (contact, QCsentinel);
3366
3367 CHECK_STRING (name);
3368
3369 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3370 ai.ai_socktype = socktype;
3371 ai.ai_protocol = 0;
3372 ai.ai_next = NULL;
3373 res = &ai;
3374
3375 /* :local ADDRESS or :remote ADDRESS */
3376 address = Fplist_get (contact, QCaddress);
3377 if (!NILP (address))
3378 {
3379 host = service = Qnil;
3380
3381 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3382 error ("Malformed :address");
3383 ai.ai_family = family;
3384 ai.ai_addr = alloca (ai.ai_addrlen);
3385 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3386 goto open_socket;
3387 }
3388
3389 /* :family FAMILY -- nil (for Inet), local, or integer. */
3390 tem = Fplist_get (contact, QCfamily);
3391 if (NILP (tem))
3392 {
3393 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3394 family = AF_UNSPEC;
3395 #else
3396 family = AF_INET;
3397 #endif
3398 }
3399 #ifdef HAVE_LOCAL_SOCKETS
3400 else if (EQ (tem, Qlocal))
3401 family = AF_LOCAL;
3402 #endif
3403 #ifdef AF_INET6
3404 else if (EQ (tem, Qipv6))
3405 family = AF_INET6;
3406 #endif
3407 else if (EQ (tem, Qipv4))
3408 family = AF_INET;
3409 else if (INTEGERP (tem))
3410 family = XINT (tem);
3411 else
3412 error ("Unknown address family");
3413
3414 ai.ai_family = family;
3415
3416 /* :service SERVICE -- string, integer (port number), or t (random port). */
3417 service = Fplist_get (contact, QCservice);
3418
3419 #ifdef HAVE_LOCAL_SOCKETS
3420 if (family == AF_LOCAL)
3421 {
3422 /* Host is not used. */
3423 host = Qnil;
3424 CHECK_STRING (service);
3425 bzero (&address_un, sizeof address_un);
3426 address_un.sun_family = AF_LOCAL;
3427 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3428 ai.ai_addr = (struct sockaddr *) &address_un;
3429 ai.ai_addrlen = sizeof address_un;
3430 goto open_socket;
3431 }
3432 #endif
3433
3434 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3435 host = Fplist_get (contact, QChost);
3436 if (!NILP (host))
3437 {
3438 if (EQ (host, Qlocal))
3439 host = build_string ("localhost");
3440 CHECK_STRING (host);
3441 }
3442
3443 /* Slow down polling to every ten seconds.
3444 Some kernels have a bug which causes retrying connect to fail
3445 after a connect. Polling can interfere with gethostbyname too. */
3446 #ifdef POLL_FOR_INPUT
3447 if (socktype != SOCK_DGRAM)
3448 {
3449 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3450 bind_polling_period (10);
3451 }
3452 #endif
3453
3454 #ifdef HAVE_GETADDRINFO
3455 /* If we have a host, use getaddrinfo to resolve both host and service.
3456 Otherwise, use getservbyname to lookup the service. */
3457 if (!NILP (host))
3458 {
3459
3460 /* SERVICE can either be a string or int.
3461 Convert to a C string for later use by getaddrinfo. */
3462 if (EQ (service, Qt))
3463 portstring = "0";
3464 else if (INTEGERP (service))
3465 {
3466 sprintf (portbuf, "%ld", (long) XINT (service));
3467 portstring = portbuf;
3468 }
3469 else
3470 {
3471 CHECK_STRING (service);
3472 portstring = SDATA (service);
3473 }
3474
3475 immediate_quit = 1;
3476 QUIT;
3477 memset (&hints, 0, sizeof (hints));
3478 hints.ai_flags = 0;
3479 hints.ai_family = family;
3480 hints.ai_socktype = socktype;
3481 hints.ai_protocol = 0;
3482
3483 #ifdef HAVE_RES_INIT
3484 res_init ();
3485 #endif
3486
3487 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3488 if (ret)
3489 #ifdef HAVE_GAI_STRERROR
3490 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3491 #else
3492 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3493 #endif
3494 immediate_quit = 0;
3495
3496 goto open_socket;
3497 }
3498 #endif /* HAVE_GETADDRINFO */
3499
3500 /* We end up here if getaddrinfo is not defined, or in case no hostname
3501 has been specified (e.g. for a local server process). */
3502
3503 if (EQ (service, Qt))
3504 port = 0;
3505 else if (INTEGERP (service))
3506 port = htons ((unsigned short) XINT (service));
3507 else
3508 {
3509 struct servent *svc_info;
3510 CHECK_STRING (service);
3511 svc_info = getservbyname (SDATA (service),
3512 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3513 if (svc_info == 0)
3514 error ("Unknown service: %s", SDATA (service));
3515 port = svc_info->s_port;
3516 }
3517
3518 bzero (&address_in, sizeof address_in);
3519 address_in.sin_family = family;
3520 address_in.sin_addr.s_addr = INADDR_ANY;
3521 address_in.sin_port = port;
3522
3523 #ifndef HAVE_GETADDRINFO
3524 if (!NILP (host))
3525 {
3526 struct hostent *host_info_ptr;
3527
3528 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3529 as it may `hang' Emacs for a very long time. */
3530 immediate_quit = 1;
3531 QUIT;
3532
3533 #ifdef HAVE_RES_INIT
3534 res_init ();
3535 #endif
3536
3537 host_info_ptr = gethostbyname (SDATA (host));
3538 immediate_quit = 0;
3539
3540 if (host_info_ptr)
3541 {
3542 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3543 host_info_ptr->h_length);
3544 family = host_info_ptr->h_addrtype;
3545 address_in.sin_family = family;
3546 }
3547 else
3548 /* Attempt to interpret host as numeric inet address */
3549 {
3550 unsigned long numeric_addr;
3551 numeric_addr = inet_addr ((char *) SDATA (host));
3552 if (numeric_addr == -1)
3553 error ("Unknown host \"%s\"", SDATA (host));
3554
3555 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3556 sizeof (address_in.sin_addr));
3557 }
3558
3559 }
3560 #endif /* not HAVE_GETADDRINFO */
3561
3562 ai.ai_family = family;
3563 ai.ai_addr = (struct sockaddr *) &address_in;
3564 ai.ai_addrlen = sizeof address_in;
3565
3566 open_socket:
3567
3568 /* Do this in case we never enter the for-loop below. */
3569 count1 = SPECPDL_INDEX ();
3570 s = -1;
3571
3572 for (lres = res; lres; lres = lres->ai_next)
3573 {
3574 int optn, optbits;
3575
3576 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3577 if (s < 0)
3578 {
3579 xerrno = errno;
3580 continue;
3581 }
3582
3583 #ifdef DATAGRAM_SOCKETS
3584 if (!is_server && socktype == SOCK_DGRAM)
3585 break;
3586 #endif /* DATAGRAM_SOCKETS */
3587
3588 #ifdef NON_BLOCKING_CONNECT
3589 if (is_non_blocking_client)
3590 {
3591 #ifdef O_NONBLOCK
3592 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3593 #else
3594 ret = fcntl (s, F_SETFL, O_NDELAY);
3595 #endif
3596 if (ret < 0)
3597 {
3598 xerrno = errno;
3599 emacs_close (s);
3600 s = -1;
3601 continue;
3602 }
3603 }
3604 #endif
3605
3606 /* Make us close S if quit. */
3607 record_unwind_protect (close_file_unwind, make_number (s));
3608
3609 /* Parse network options in the arg list.
3610 We simply ignore anything which isn't a known option (including other keywords).
3611 An error is signaled if setting a known option fails. */
3612 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3613 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3614
3615 if (is_server)
3616 {
3617 /* Configure as a server socket. */
3618
3619 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3620 explicit :reuseaddr key to override this. */
3621 #ifdef HAVE_LOCAL_SOCKETS
3622 if (family != AF_LOCAL)
3623 #endif
3624 if (!(optbits & (1 << OPIX_REUSEADDR)))
3625 {
3626 int optval = 1;
3627 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3628 report_file_error ("Cannot set reuse option on server socket", Qnil);
3629 }
3630
3631 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3632 report_file_error ("Cannot bind server socket", Qnil);
3633
3634 #ifdef HAVE_GETSOCKNAME
3635 if (EQ (service, Qt))
3636 {
3637 struct sockaddr_in sa1;
3638 int len1 = sizeof (sa1);
3639 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3640 {
3641 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3642 service = make_number (ntohs (sa1.sin_port));
3643 contact = Fplist_put (contact, QCservice, service);
3644 }
3645 }
3646 #endif
3647
3648 if (socktype != SOCK_DGRAM && listen (s, backlog))
3649 report_file_error ("Cannot listen on server socket", Qnil);
3650
3651 break;
3652 }
3653
3654 immediate_quit = 1;
3655 QUIT;
3656
3657 /* This turns off all alarm-based interrupts; the
3658 bind_polling_period call above doesn't always turn all the
3659 short-interval ones off, especially if interrupt_input is
3660 set.
3661
3662 It'd be nice to be able to control the connect timeout
3663 though. Would non-blocking connect calls be portable?
3664
3665 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3666
3667 turn_on_atimers (0);
3668
3669 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3670 xerrno = errno;
3671
3672 turn_on_atimers (1);
3673
3674 if (ret == 0 || xerrno == EISCONN)
3675 {
3676 /* The unwind-protect will be discarded afterwards.
3677 Likewise for immediate_quit. */
3678 break;
3679 }
3680
3681 #ifdef NON_BLOCKING_CONNECT
3682 #ifdef EINPROGRESS
3683 if (is_non_blocking_client && xerrno == EINPROGRESS)
3684 break;
3685 #else
3686 #ifdef EWOULDBLOCK
3687 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3688 break;
3689 #endif
3690 #endif
3691 #endif
3692 if (xerrno == EINTR)
3693 {
3694 /* Unlike most other syscalls connect() cannot be called
3695 again. (That would return EALREADY.) The proper way to
3696 wait for completion is select(). */
3697 int sc;
3698 SELECT_TYPE fdset;
3699 retry_select:
3700 FD_ZERO (&fdset);
3701 FD_SET (s, &fdset);
3702 QUIT;
3703 sc = select (s + 1, (SELECT_TYPE *)0, &fdset, (SELECT_TYPE *)0,
3704 (EMACS_TIME *)0);
3705 if (sc == -1)
3706 {
3707 if (errno == EINTR)
3708 goto retry_select;
3709 else
3710 report_file_error ("select failed", Qnil);
3711 }
3712 eassert (sc > 0);
3713 {
3714 int len = sizeof xerrno;
3715 eassert (FD_ISSET (s, &fdset));
3716 if (getsockopt (s, SOL_SOCKET, SO_ERROR, &xerrno, &len) == -1)
3717 report_file_error ("getsockopt failed", Qnil);
3718 if (xerrno != 0)
3719 errno = xerrno, report_file_error ("error during connect", Qnil);
3720 else
3721 break;
3722 }
3723 }
3724
3725 immediate_quit = 0;
3726
3727 /* Discard the unwind protect closing S. */
3728 specpdl_ptr = specpdl + count1;
3729 emacs_close (s);
3730 s = -1;
3731 }
3732
3733 if (s >= 0)
3734 {
3735 #ifdef DATAGRAM_SOCKETS
3736 if (socktype == SOCK_DGRAM)
3737 {
3738 if (datagram_address[s].sa)
3739 abort ();
3740 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3741 datagram_address[s].len = lres->ai_addrlen;
3742 if (is_server)
3743 {
3744 Lisp_Object remote;
3745 bzero (datagram_address[s].sa, lres->ai_addrlen);
3746 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3747 {
3748 int rfamily, rlen;
3749 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3750 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3751 conv_lisp_to_sockaddr (rfamily, remote,
3752 datagram_address[s].sa, rlen);
3753 }
3754 }
3755 else
3756 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3757 }
3758 #endif
3759 contact = Fplist_put (contact, QCaddress,
3760 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3761 #ifdef HAVE_GETSOCKNAME
3762 if (!is_server)
3763 {
3764 struct sockaddr_in sa1;
3765 int len1 = sizeof (sa1);
3766 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3767 contact = Fplist_put (contact, QClocal,
3768 conv_sockaddr_to_lisp (&sa1, len1));
3769 }
3770 #endif
3771 }
3772
3773 immediate_quit = 0;
3774
3775 #ifdef HAVE_GETADDRINFO
3776 if (res != &ai)
3777 {
3778 BLOCK_INPUT;
3779 freeaddrinfo (res);
3780 UNBLOCK_INPUT;
3781 }
3782 #endif
3783
3784 /* Discard the unwind protect for closing S, if any. */
3785 specpdl_ptr = specpdl + count1;
3786
3787 /* Unwind bind_polling_period and request_sigio. */
3788 unbind_to (count, Qnil);
3789
3790 if (s < 0)
3791 {
3792 /* If non-blocking got this far - and failed - assume non-blocking is
3793 not supported after all. This is probably a wrong assumption, but
3794 the normal blocking calls to open-network-stream handles this error
3795 better. */
3796 if (is_non_blocking_client)
3797 return Qnil;
3798
3799 errno = xerrno;
3800 if (is_server)
3801 report_file_error ("make server process failed", contact);
3802 else
3803 report_file_error ("make client process failed", contact);
3804 }
3805
3806 inch = s;
3807 outch = s;
3808
3809 if (!NILP (buffer))
3810 buffer = Fget_buffer_create (buffer);
3811 proc = make_process (name);
3812
3813 chan_process[inch] = proc;
3814
3815 #ifdef O_NONBLOCK
3816 fcntl (inch, F_SETFL, O_NONBLOCK);
3817 #else
3818 #ifdef O_NDELAY
3819 fcntl (inch, F_SETFL, O_NDELAY);
3820 #endif
3821 #endif
3822
3823 p = XPROCESS (proc);
3824
3825 p->childp = contact;
3826 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3827 p->type = Qnetwork;
3828
3829 p->buffer = buffer;
3830 p->sentinel = sentinel;
3831 p->filter = filter;
3832 p->log = Fplist_get (contact, QClog);
3833 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3834 p->kill_without_query = 1;
3835 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3836 p->command = Qt;
3837 p->pid = 0;
3838 p->infd = inch;
3839 p->outfd = outch;
3840 if (is_server && socktype != SOCK_DGRAM)
3841 p->status = Qlisten;
3842
3843 /* Make the process marker point into the process buffer (if any). */
3844 if (BUFFERP (buffer))
3845 set_marker_both (p->mark, buffer,
3846 BUF_ZV (XBUFFER (buffer)),
3847 BUF_ZV_BYTE (XBUFFER (buffer)));
3848
3849 #ifdef NON_BLOCKING_CONNECT
3850 if (is_non_blocking_client)
3851 {
3852 /* We may get here if connect did succeed immediately. However,
3853 in that case, we still need to signal this like a non-blocking
3854 connection. */
3855 p->status = Qconnect;
3856 if (!FD_ISSET (inch, &connect_wait_mask))
3857 {
3858 FD_SET (inch, &connect_wait_mask);
3859 num_pending_connects++;
3860 }
3861 }
3862 else
3863 #endif
3864 /* A server may have a client filter setting of Qt, but it must
3865 still listen for incoming connects unless it is stopped. */
3866 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3867 || (EQ (p->status, Qlisten) && NILP (p->command)))
3868 {
3869 FD_SET (inch, &input_wait_mask);
3870 FD_SET (inch, &non_keyboard_wait_mask);
3871 }
3872
3873 if (inch > max_process_desc)
3874 max_process_desc = inch;
3875
3876 tem = Fplist_member (contact, QCcoding);
3877 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3878 tem = Qnil; /* No error message (too late!). */
3879
3880 {
3881 /* Setup coding systems for communicating with the network stream. */
3882 struct gcpro gcpro1;
3883 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3884 Lisp_Object coding_systems = Qt;
3885 Lisp_Object args[5], val;
3886
3887 if (!NILP (tem))
3888 {
3889 val = XCAR (XCDR (tem));
3890 if (CONSP (val))
3891 val = XCAR (val);
3892 }
3893 else if (!NILP (Vcoding_system_for_read))
3894 val = Vcoding_system_for_read;
3895 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3896 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3897 /* We dare not decode end-of-line format by setting VAL to
3898 Qraw_text, because the existing Emacs Lisp libraries
3899 assume that they receive bare code including a sequene of
3900 CR LF. */
3901 val = Qnil;
3902 else
3903 {
3904 if (NILP (host) || NILP (service))
3905 coding_systems = Qnil;
3906 else
3907 {
3908 args[0] = Qopen_network_stream, args[1] = name,
3909 args[2] = buffer, args[3] = host, args[4] = service;
3910 GCPRO1 (proc);
3911 coding_systems = Ffind_operation_coding_system (5, args);
3912 UNGCPRO;
3913 }
3914 if (CONSP (coding_systems))
3915 val = XCAR (coding_systems);
3916 else if (CONSP (Vdefault_process_coding_system))
3917 val = XCAR (Vdefault_process_coding_system);
3918 else
3919 val = Qnil;
3920 }
3921 p->decode_coding_system = val;
3922
3923 if (!NILP (tem))
3924 {
3925 val = XCAR (XCDR (tem));
3926 if (CONSP (val))
3927 val = XCDR (val);
3928 }
3929 else if (!NILP (Vcoding_system_for_write))
3930 val = Vcoding_system_for_write;
3931 else if (NILP (current_buffer->enable_multibyte_characters))
3932 val = Qnil;
3933 else
3934 {
3935 if (EQ (coding_systems, Qt))
3936 {
3937 if (NILP (host) || NILP (service))
3938 coding_systems = Qnil;
3939 else
3940 {
3941 args[0] = Qopen_network_stream, args[1] = name,
3942 args[2] = buffer, args[3] = host, args[4] = service;
3943 GCPRO1 (proc);
3944 coding_systems = Ffind_operation_coding_system (5, args);
3945 UNGCPRO;
3946 }
3947 }
3948 if (CONSP (coding_systems))
3949 val = XCDR (coding_systems);
3950 else if (CONSP (Vdefault_process_coding_system))
3951 val = XCDR (Vdefault_process_coding_system);
3952 else
3953 val = Qnil;
3954 }
3955 p->encode_coding_system = val;
3956 }
3957 setup_process_coding_systems (proc);
3958
3959 p->decoding_buf = make_uninit_string (0);
3960 p->decoding_carryover = 0;
3961 p->encoding_buf = make_uninit_string (0);
3962
3963 p->inherit_coding_system_flag
3964 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3965
3966 UNGCPRO;
3967 return proc;
3968 }
3969 #endif /* HAVE_SOCKETS */
3970
3971 \f
3972 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3973
3974 #ifdef SIOCGIFCONF
3975 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3976 doc: /* Return an alist of all network interfaces and their network address.
3977 Each element is a cons, the car of which is a string containing the
3978 interface name, and the cdr is the network address in internal
3979 format; see the description of ADDRESS in `make-network-process'. */)
3980 ()
3981 {
3982 struct ifconf ifconf;
3983 struct ifreq *ifreqs = NULL;
3984 int ifaces = 0;
3985 int buf_size, s;
3986 Lisp_Object res;
3987
3988 s = socket (AF_INET, SOCK_STREAM, 0);
3989 if (s < 0)
3990 return Qnil;
3991
3992 again:
3993 ifaces += 25;
3994 buf_size = ifaces * sizeof(ifreqs[0]);
3995 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3996 if (!ifreqs)
3997 {
3998 close (s);
3999 return Qnil;
4000 }
4001
4002 ifconf.ifc_len = buf_size;
4003 ifconf.ifc_req = ifreqs;
4004 if (ioctl (s, SIOCGIFCONF, &ifconf))
4005 {
4006 close (s);
4007 return Qnil;
4008 }
4009
4010 if (ifconf.ifc_len == buf_size)
4011 goto again;
4012
4013 close (s);
4014 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
4015
4016 res = Qnil;
4017 while (--ifaces >= 0)
4018 {
4019 struct ifreq *ifq = &ifreqs[ifaces];
4020 char namebuf[sizeof (ifq->ifr_name) + 1];
4021 if (ifq->ifr_addr.sa_family != AF_INET)
4022 continue;
4023 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
4024 namebuf[sizeof (ifq->ifr_name)] = 0;
4025 res = Fcons (Fcons (build_string (namebuf),
4026 conv_sockaddr_to_lisp (&ifq->ifr_addr,
4027 sizeof (struct sockaddr))),
4028 res);
4029 }
4030
4031 return res;
4032 }
4033 #endif /* SIOCGIFCONF */
4034
4035 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
4036
4037 struct ifflag_def {
4038 int flag_bit;
4039 const char *flag_sym;
4040 };
4041
4042 static const struct ifflag_def ifflag_table[] = {
4043 #ifdef IFF_UP
4044 { IFF_UP, "up" },
4045 #endif
4046 #ifdef IFF_BROADCAST
4047 { IFF_BROADCAST, "broadcast" },
4048 #endif
4049 #ifdef IFF_DEBUG
4050 { IFF_DEBUG, "debug" },
4051 #endif
4052 #ifdef IFF_LOOPBACK
4053 { IFF_LOOPBACK, "loopback" },
4054 #endif
4055 #ifdef IFF_POINTOPOINT
4056 { IFF_POINTOPOINT, "pointopoint" },
4057 #endif
4058 #ifdef IFF_RUNNING
4059 { IFF_RUNNING, "running" },
4060 #endif
4061 #ifdef IFF_NOARP
4062 { IFF_NOARP, "noarp" },
4063 #endif
4064 #ifdef IFF_PROMISC
4065 { IFF_PROMISC, "promisc" },
4066 #endif
4067 #ifdef IFF_NOTRAILERS
4068 { IFF_NOTRAILERS, "notrailers" },
4069 #endif
4070 #ifdef IFF_ALLMULTI
4071 { IFF_ALLMULTI, "allmulti" },
4072 #endif
4073 #ifdef IFF_MASTER
4074 { IFF_MASTER, "master" },
4075 #endif
4076 #ifdef IFF_SLAVE
4077 { IFF_SLAVE, "slave" },
4078 #endif
4079 #ifdef IFF_MULTICAST
4080 { IFF_MULTICAST, "multicast" },
4081 #endif
4082 #ifdef IFF_PORTSEL
4083 { IFF_PORTSEL, "portsel" },
4084 #endif
4085 #ifdef IFF_AUTOMEDIA
4086 { IFF_AUTOMEDIA, "automedia" },
4087 #endif
4088 #ifdef IFF_DYNAMIC
4089 { IFF_DYNAMIC, "dynamic" },
4090 #endif
4091 #ifdef IFF_OACTIVE
4092 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
4093 #endif
4094 #ifdef IFF_SIMPLEX
4095 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
4096 #endif
4097 #ifdef IFF_LINK0
4098 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
4099 #endif
4100 #ifdef IFF_LINK1
4101 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
4102 #endif
4103 #ifdef IFF_LINK2
4104 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
4105 #endif
4106 { 0, 0 }
4107 };
4108
4109 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
4110 doc: /* Return information about network interface named IFNAME.
4111 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
4112 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
4113 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
4114 FLAGS is the current flags of the interface. */)
4115 (ifname)
4116 Lisp_Object ifname;
4117 {
4118 struct ifreq rq;
4119 Lisp_Object res = Qnil;
4120 Lisp_Object elt;
4121 int s;
4122 int any = 0;
4123
4124 CHECK_STRING (ifname);
4125
4126 bzero (rq.ifr_name, sizeof rq.ifr_name);
4127 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
4128
4129 s = socket (AF_INET, SOCK_STREAM, 0);
4130 if (s < 0)
4131 return Qnil;
4132
4133 elt = Qnil;
4134 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
4135 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
4136 {
4137 int flags = rq.ifr_flags;
4138 const struct ifflag_def *fp;
4139 int fnum;
4140
4141 any++;
4142 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
4143 {
4144 if (flags & fp->flag_bit)
4145 {
4146 elt = Fcons (intern (fp->flag_sym), elt);
4147 flags -= fp->flag_bit;
4148 }
4149 }
4150 for (fnum = 0; flags && fnum < 32; fnum++)
4151 {
4152 if (flags & (1 << fnum))
4153 {
4154 elt = Fcons (make_number (fnum), elt);
4155 }
4156 }
4157 }
4158 #endif
4159 res = Fcons (elt, res);
4160
4161 elt = Qnil;
4162 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
4163 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4164 {
4165 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4166 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4167 int n;
4168
4169 any++;
4170 for (n = 0; n < 6; n++)
4171 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4172 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4173 }
4174 #endif
4175 res = Fcons (elt, res);
4176
4177 elt = Qnil;
4178 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4179 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4180 {
4181 any++;
4182 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4183 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4184 #else
4185 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4186 #endif
4187 }
4188 #endif
4189 res = Fcons (elt, res);
4190
4191 elt = Qnil;
4192 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4193 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4194 {
4195 any++;
4196 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4197 }
4198 #endif
4199 res = Fcons (elt, res);
4200
4201 elt = Qnil;
4202 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4203 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4204 {
4205 any++;
4206 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4207 }
4208 #endif
4209 res = Fcons (elt, res);
4210
4211 close (s);
4212
4213 return any ? res : Qnil;
4214 }
4215 #endif
4216 #endif /* HAVE_SOCKETS */
4217
4218 /* Turn off input and output for process PROC. */
4219
4220 void
4221 deactivate_process (proc)
4222 Lisp_Object proc;
4223 {
4224 register int inchannel, outchannel;
4225 register struct Lisp_Process *p = XPROCESS (proc);
4226
4227 inchannel = p->infd;
4228 outchannel = p->outfd;
4229
4230 #ifdef ADAPTIVE_READ_BUFFERING
4231 if (p->read_output_delay > 0)
4232 {
4233 if (--process_output_delay_count < 0)
4234 process_output_delay_count = 0;
4235 p->read_output_delay = 0;
4236 p->read_output_skip = 0;
4237 }
4238 #endif
4239
4240 if (inchannel >= 0)
4241 {
4242 /* Beware SIGCHLD hereabouts. */
4243 flush_pending_output (inchannel);
4244 emacs_close (inchannel);
4245 if (outchannel >= 0 && outchannel != inchannel)
4246 emacs_close (outchannel);
4247
4248 p->infd = -1;
4249 p->outfd = -1;
4250 #ifdef DATAGRAM_SOCKETS
4251 if (DATAGRAM_CHAN_P (inchannel))
4252 {
4253 xfree (datagram_address[inchannel].sa);
4254 datagram_address[inchannel].sa = 0;
4255 datagram_address[inchannel].len = 0;
4256 }
4257 #endif
4258 chan_process[inchannel] = Qnil;
4259 FD_CLR (inchannel, &input_wait_mask);
4260 FD_CLR (inchannel, &non_keyboard_wait_mask);
4261 #ifdef NON_BLOCKING_CONNECT
4262 if (FD_ISSET (inchannel, &connect_wait_mask))
4263 {
4264 FD_CLR (inchannel, &connect_wait_mask);
4265 if (--num_pending_connects < 0)
4266 abort ();
4267 }
4268 #endif
4269 if (inchannel == max_process_desc)
4270 {
4271 int i;
4272 /* We just closed the highest-numbered process input descriptor,
4273 so recompute the highest-numbered one now. */
4274 max_process_desc = 0;
4275 for (i = 0; i < MAXDESC; i++)
4276 if (!NILP (chan_process[i]))
4277 max_process_desc = i;
4278 }
4279 }
4280 }
4281
4282 /* Close all descriptors currently in use for communication
4283 with subprocess. This is used in a newly-forked subprocess
4284 to get rid of irrelevant descriptors. */
4285
4286 void
4287 close_process_descs ()
4288 {
4289 #ifndef WINDOWSNT
4290 int i;
4291 for (i = 0; i < MAXDESC; i++)
4292 {
4293 Lisp_Object process;
4294 process = chan_process[i];
4295 if (!NILP (process))
4296 {
4297 int in = XPROCESS (process)->infd;
4298 int out = XPROCESS (process)->outfd;
4299 if (in >= 0)
4300 emacs_close (in);
4301 if (out >= 0 && in != out)
4302 emacs_close (out);
4303 }
4304 }
4305 #endif
4306 }
4307 \f
4308 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4309 0, 4, 0,
4310 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4311 It is read into the process' buffers or given to their filter functions.
4312 Non-nil arg PROCESS means do not return until some output has been received
4313 from PROCESS.
4314
4315 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4316 and milliseconds to wait; return after that much time whether or not
4317 there is any subprocess output. If SECONDS is a floating point number,
4318 it specifies a fractional number of seconds to wait.
4319 The MILLISEC argument is obsolete and should be avoided.
4320
4321 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4322 from PROCESS, suspending reading output from other processes.
4323 If JUST-THIS-ONE is an integer, don't run any timers either.
4324 Return non-nil if we received any output before the timeout expired. */)
4325 (process, seconds, millisec, just_this_one)
4326 register Lisp_Object process, seconds, millisec, just_this_one;
4327 {
4328 int secs, usecs = 0;
4329
4330 if (! NILP (process))
4331 CHECK_PROCESS (process);
4332 else
4333 just_this_one = Qnil;
4334
4335 if (!NILP (millisec))
4336 { /* Obsolete calling convention using integers rather than floats. */
4337 CHECK_NUMBER (millisec);
4338 if (NILP (seconds))
4339 seconds = make_float (XINT (millisec) / 1000.0);
4340 else
4341 {
4342 CHECK_NUMBER (seconds);
4343 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4344 }
4345 }
4346
4347 if (!NILP (seconds))
4348 {
4349 if (INTEGERP (seconds))
4350 secs = XINT (seconds);
4351 else if (FLOATP (seconds))
4352 {
4353 double timeout = XFLOAT_DATA (seconds);
4354 secs = (int) timeout;
4355 usecs = (int) ((timeout - (double) secs) * 1000000);
4356 }
4357 else
4358 wrong_type_argument (Qnumberp, seconds);
4359
4360 if (secs < 0 || (secs == 0 && usecs == 0))
4361 secs = -1, usecs = 0;
4362 }
4363 else
4364 secs = NILP (process) ? -1 : 0;
4365
4366 return
4367 (wait_reading_process_output (secs, usecs, 0, 0,
4368 Qnil,
4369 !NILP (process) ? XPROCESS (process) : NULL,
4370 NILP (just_this_one) ? 0 :
4371 !INTEGERP (just_this_one) ? 1 : -1)
4372 ? Qt : Qnil);
4373 }
4374
4375 /* Accept a connection for server process SERVER on CHANNEL. */
4376
4377 static int connect_counter = 0;
4378
4379 static void
4380 server_accept_connection (server, channel)
4381 Lisp_Object server;
4382 int channel;
4383 {
4384 Lisp_Object proc, caller, name, buffer;
4385 Lisp_Object contact, host, service;
4386 struct Lisp_Process *ps= XPROCESS (server);
4387 struct Lisp_Process *p;
4388 int s;
4389 union u_sockaddr {
4390 struct sockaddr sa;
4391 struct sockaddr_in in;
4392 #ifdef AF_INET6
4393 struct sockaddr_in6 in6;
4394 #endif
4395 #ifdef HAVE_LOCAL_SOCKETS
4396 struct sockaddr_un un;
4397 #endif
4398 } saddr;
4399 int len = sizeof saddr;
4400
4401 s = accept (channel, &saddr.sa, &len);
4402
4403 if (s < 0)
4404 {
4405 int code = errno;
4406
4407 if (code == EAGAIN)
4408 return;
4409 #ifdef EWOULDBLOCK
4410 if (code == EWOULDBLOCK)
4411 return;
4412 #endif
4413
4414 if (!NILP (ps->log))
4415 call3 (ps->log, server, Qnil,
4416 concat3 (build_string ("accept failed with code"),
4417 Fnumber_to_string (make_number (code)),
4418 build_string ("\n")));
4419 return;
4420 }
4421
4422 connect_counter++;
4423
4424 /* Setup a new process to handle the connection. */
4425
4426 /* Generate a unique identification of the caller, and build contact
4427 information for this process. */
4428 host = Qt;
4429 service = Qnil;
4430 switch (saddr.sa.sa_family)
4431 {
4432 case AF_INET:
4433 {
4434 Lisp_Object args[5];
4435 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4436 args[0] = build_string ("%d.%d.%d.%d");
4437 args[1] = make_number (*ip++);
4438 args[2] = make_number (*ip++);
4439 args[3] = make_number (*ip++);
4440 args[4] = make_number (*ip++);
4441 host = Fformat (5, args);
4442 service = make_number (ntohs (saddr.in.sin_port));
4443
4444 args[0] = build_string (" <%s:%d>");
4445 args[1] = host;
4446 args[2] = service;
4447 caller = Fformat (3, args);
4448 }
4449 break;
4450
4451 #ifdef AF_INET6
4452 case AF_INET6:
4453 {
4454 Lisp_Object args[9];
4455 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4456 int i;
4457 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4458 for (i = 0; i < 8; i++)
4459 args[i+1] = make_number (ntohs(ip6[i]));
4460 host = Fformat (9, args);
4461 service = make_number (ntohs (saddr.in.sin_port));
4462
4463 args[0] = build_string (" <[%s]:%d>");
4464 args[1] = host;
4465 args[2] = service;
4466 caller = Fformat (3, args);
4467 }
4468 break;
4469 #endif
4470
4471 #ifdef HAVE_LOCAL_SOCKETS
4472 case AF_LOCAL:
4473 #endif
4474 default:
4475 caller = Fnumber_to_string (make_number (connect_counter));
4476 caller = concat3 (build_string (" <"), caller, build_string (">"));
4477 break;
4478 }
4479
4480 /* Create a new buffer name for this process if it doesn't have a
4481 filter. The new buffer name is based on the buffer name or
4482 process name of the server process concatenated with the caller
4483 identification. */
4484
4485 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4486 buffer = Qnil;
4487 else
4488 {
4489 buffer = ps->buffer;
4490 if (!NILP (buffer))
4491 buffer = Fbuffer_name (buffer);
4492 else
4493 buffer = ps->name;
4494 if (!NILP (buffer))
4495 {
4496 buffer = concat2 (buffer, caller);
4497 buffer = Fget_buffer_create (buffer);
4498 }
4499 }
4500
4501 /* Generate a unique name for the new server process. Combine the
4502 server process name with the caller identification. */
4503
4504 name = concat2 (ps->name, caller);
4505 proc = make_process (name);
4506
4507 chan_process[s] = proc;
4508
4509 #ifdef O_NONBLOCK
4510 fcntl (s, F_SETFL, O_NONBLOCK);
4511 #else
4512 #ifdef O_NDELAY
4513 fcntl (s, F_SETFL, O_NDELAY);
4514 #endif
4515 #endif
4516
4517 p = XPROCESS (proc);
4518
4519 /* Build new contact information for this setup. */
4520 contact = Fcopy_sequence (ps->childp);
4521 contact = Fplist_put (contact, QCserver, Qnil);
4522 contact = Fplist_put (contact, QChost, host);
4523 if (!NILP (service))
4524 contact = Fplist_put (contact, QCservice, service);
4525 contact = Fplist_put (contact, QCremote,
4526 conv_sockaddr_to_lisp (&saddr.sa, len));
4527 #ifdef HAVE_GETSOCKNAME
4528 len = sizeof saddr;
4529 if (getsockname (s, &saddr.sa, &len) == 0)
4530 contact = Fplist_put (contact, QClocal,
4531 conv_sockaddr_to_lisp (&saddr.sa, len));
4532 #endif
4533
4534 p->childp = contact;
4535 p->plist = Fcopy_sequence (ps->plist);
4536 p->type = Qnetwork;
4537
4538 p->buffer = buffer;
4539 p->sentinel = ps->sentinel;
4540 p->filter = ps->filter;
4541 p->command = Qnil;
4542 p->pid = 0;
4543 p->infd = s;
4544 p->outfd = s;
4545 p->status = Qrun;
4546
4547 /* Client processes for accepted connections are not stopped initially. */
4548 if (!EQ (p->filter, Qt))
4549 {
4550 FD_SET (s, &input_wait_mask);
4551 FD_SET (s, &non_keyboard_wait_mask);
4552 }
4553
4554 if (s > max_process_desc)
4555 max_process_desc = s;
4556
4557 /* Setup coding system for new process based on server process.
4558 This seems to be the proper thing to do, as the coding system
4559 of the new process should reflect the settings at the time the
4560 server socket was opened; not the current settings. */
4561
4562 p->decode_coding_system = ps->decode_coding_system;
4563 p->encode_coding_system = ps->encode_coding_system;
4564 setup_process_coding_systems (proc);
4565
4566 p->decoding_buf = make_uninit_string (0);
4567 p->decoding_carryover = 0;
4568 p->encoding_buf = make_uninit_string (0);
4569
4570 p->inherit_coding_system_flag
4571 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4572
4573 if (!NILP (ps->log))
4574 call3 (ps->log, server, proc,
4575 concat3 (build_string ("accept from "),
4576 (STRINGP (host) ? host : build_string ("-")),
4577 build_string ("\n")));
4578
4579 if (!NILP (p->sentinel))
4580 exec_sentinel (proc,
4581 concat3 (build_string ("open from "),
4582 (STRINGP (host) ? host : build_string ("-")),
4583 build_string ("\n")));
4584 }
4585
4586 /* This variable is different from waiting_for_input in keyboard.c.
4587 It is used to communicate to a lisp process-filter/sentinel (via the
4588 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4589 for user-input when that process-filter was called.
4590 waiting_for_input cannot be used as that is by definition 0 when
4591 lisp code is being evalled.
4592 This is also used in record_asynch_buffer_change.
4593 For that purpose, this must be 0
4594 when not inside wait_reading_process_output. */
4595 static int waiting_for_user_input_p;
4596
4597 static Lisp_Object
4598 wait_reading_process_output_unwind (data)
4599 Lisp_Object data;
4600 {
4601 waiting_for_user_input_p = XINT (data);
4602 return Qnil;
4603 }
4604
4605 /* This is here so breakpoints can be put on it. */
4606 static void
4607 wait_reading_process_output_1 ()
4608 {
4609 }
4610
4611 /* Use a wrapper around select to work around a bug in gdb 5.3.
4612 Normally, the wrapper is optimized away by inlining.
4613
4614 If emacs is stopped inside select, the gdb backtrace doesn't
4615 show the function which called select, so it is practically
4616 impossible to step through wait_reading_process_output. */
4617
4618 #ifndef select
4619 static INLINE int
4620 select_wrapper (n, rfd, wfd, xfd, tmo)
4621 int n;
4622 SELECT_TYPE *rfd, *wfd, *xfd;
4623 EMACS_TIME *tmo;
4624 {
4625 return select (n, rfd, wfd, xfd, tmo);
4626 }
4627 #define select select_wrapper
4628 #endif
4629
4630 /* Read and dispose of subprocess output while waiting for timeout to
4631 elapse and/or keyboard input to be available.
4632
4633 TIME_LIMIT is:
4634 timeout in seconds, or
4635 zero for no limit, or
4636 -1 means gobble data immediately available but don't wait for any.
4637
4638 MICROSECS is:
4639 an additional duration to wait, measured in microseconds.
4640 If this is nonzero and time_limit is 0, then the timeout
4641 consists of MICROSECS only.
4642
4643 READ_KBD is a lisp value:
4644 0 to ignore keyboard input, or
4645 1 to return when input is available, or
4646 -1 meaning caller will actually read the input, so don't throw to
4647 the quit handler, or
4648
4649 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4650 output that arrives.
4651
4652 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4653 (and gobble terminal input into the buffer if any arrives).
4654
4655 If WAIT_PROC is specified, wait until something arrives from that
4656 process. The return value is true if we read some input from
4657 that process.
4658
4659 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4660 (suspending output from other processes). A negative value
4661 means don't run any timers either.
4662
4663 If WAIT_PROC is specified, then the function returns true if we
4664 received input from that process before the timeout elapsed.
4665 Otherwise, return true if we received input from any process. */
4666
4667 int
4668 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4669 wait_for_cell, wait_proc, just_wait_proc)
4670 int time_limit, microsecs, read_kbd, do_display;
4671 Lisp_Object wait_for_cell;
4672 struct Lisp_Process *wait_proc;
4673 int just_wait_proc;
4674 {
4675 register int channel, nfds;
4676 SELECT_TYPE Available;
4677 #ifdef NON_BLOCKING_CONNECT
4678 SELECT_TYPE Connecting;
4679 int check_connect;
4680 #endif
4681 int check_delay, no_avail;
4682 int xerrno;
4683 Lisp_Object proc;
4684 EMACS_TIME timeout, end_time;
4685 int wait_channel = -1;
4686 int got_some_input = 0;
4687 int count = SPECPDL_INDEX ();
4688
4689 FD_ZERO (&Available);
4690 #ifdef NON_BLOCKING_CONNECT
4691 FD_ZERO (&Connecting);
4692 #endif
4693
4694 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4695 if (wait_proc != NULL)
4696 wait_channel = wait_proc->infd;
4697
4698 record_unwind_protect (wait_reading_process_output_unwind,
4699 make_number (waiting_for_user_input_p));
4700 waiting_for_user_input_p = read_kbd;
4701
4702 /* Since we may need to wait several times,
4703 compute the absolute time to return at. */
4704 if (time_limit || microsecs)
4705 {
4706 EMACS_GET_TIME (end_time);
4707 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4708 EMACS_ADD_TIME (end_time, end_time, timeout);
4709 }
4710
4711 while (1)
4712 {
4713 int timeout_reduced_for_timers = 0;
4714
4715 /* If calling from keyboard input, do not quit
4716 since we want to return C-g as an input character.
4717 Otherwise, do pending quit if requested. */
4718 if (read_kbd >= 0)
4719 QUIT;
4720 #ifdef SYNC_INPUT
4721 else
4722 process_pending_signals ();
4723 #endif
4724
4725 /* Exit now if the cell we're waiting for became non-nil. */
4726 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4727 break;
4728
4729 /* Compute time from now till when time limit is up */
4730 /* Exit if already run out */
4731 if (time_limit == -1)
4732 {
4733 /* -1 specified for timeout means
4734 gobble output available now
4735 but don't wait at all. */
4736
4737 EMACS_SET_SECS_USECS (timeout, 0, 0);
4738 }
4739 else if (time_limit || microsecs)
4740 {
4741 EMACS_GET_TIME (timeout);
4742 EMACS_SUB_TIME (timeout, end_time, timeout);
4743 if (EMACS_TIME_NEG_P (timeout))
4744 break;
4745 }
4746 else
4747 {
4748 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4749 }
4750
4751 /* Normally we run timers here.
4752 But not if wait_for_cell; in those cases,
4753 the wait is supposed to be short,
4754 and those callers cannot handle running arbitrary Lisp code here. */
4755 if (NILP (wait_for_cell)
4756 && just_wait_proc >= 0)
4757 {
4758 EMACS_TIME timer_delay;
4759
4760 do
4761 {
4762 int old_timers_run = timers_run;
4763 struct buffer *old_buffer = current_buffer;
4764 Lisp_Object old_window = selected_window;
4765
4766 timer_delay = timer_check (1);
4767
4768 /* If a timer has run, this might have changed buffers
4769 an alike. Make read_key_sequence aware of that. */
4770 if (timers_run != old_timers_run
4771 && (old_buffer != current_buffer
4772 || !EQ (old_window, selected_window))
4773 && waiting_for_user_input_p == -1)
4774 record_asynch_buffer_change ();
4775
4776 if (timers_run != old_timers_run && do_display)
4777 /* We must retry, since a timer may have requeued itself
4778 and that could alter the time_delay. */
4779 redisplay_preserve_echo_area (9);
4780 else
4781 break;
4782 }
4783 while (!detect_input_pending ());
4784
4785 /* If there is unread keyboard input, also return. */
4786 if (read_kbd != 0
4787 && requeued_events_pending_p ())
4788 break;
4789
4790 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4791 {
4792 EMACS_TIME difference;
4793 EMACS_SUB_TIME (difference, timer_delay, timeout);
4794 if (EMACS_TIME_NEG_P (difference))
4795 {
4796 timeout = timer_delay;
4797 timeout_reduced_for_timers = 1;
4798 }
4799 }
4800 /* If time_limit is -1, we are not going to wait at all. */
4801 else if (time_limit != -1)
4802 {
4803 /* This is so a breakpoint can be put here. */
4804 wait_reading_process_output_1 ();
4805 }
4806 }
4807
4808 /* Cause C-g and alarm signals to take immediate action,
4809 and cause input available signals to zero out timeout.
4810
4811 It is important that we do this before checking for process
4812 activity. If we get a SIGCHLD after the explicit checks for
4813 process activity, timeout is the only way we will know. */
4814 if (read_kbd < 0)
4815 set_waiting_for_input (&timeout);
4816
4817 /* If status of something has changed, and no input is
4818 available, notify the user of the change right away. After
4819 this explicit check, we'll let the SIGCHLD handler zap
4820 timeout to get our attention. */
4821 if (update_tick != process_tick)
4822 {
4823 SELECT_TYPE Atemp;
4824 #ifdef NON_BLOCKING_CONNECT
4825 SELECT_TYPE Ctemp;
4826 #endif
4827
4828 if (kbd_on_hold_p ())
4829 FD_ZERO (&Atemp);
4830 else
4831 Atemp = input_wait_mask;
4832
4833 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4834
4835 EMACS_SET_SECS_USECS (timeout, 0, 0);
4836 if ((select (max (max (max_process_desc, max_keyboard_desc),
4837 max_gpm_desc) + 1,
4838 &Atemp,
4839 #ifdef NON_BLOCKING_CONNECT
4840 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4841 #else
4842 (SELECT_TYPE *)0,
4843 #endif
4844 (SELECT_TYPE *)0, &timeout)
4845 <= 0))
4846 {
4847 /* It's okay for us to do this and then continue with
4848 the loop, since timeout has already been zeroed out. */
4849 clear_waiting_for_input ();
4850 status_notify (NULL);
4851 if (do_display) redisplay_preserve_echo_area (13);
4852 }
4853 }
4854
4855 /* Don't wait for output from a non-running process. Just
4856 read whatever data has already been received. */
4857 if (wait_proc && wait_proc->raw_status_new)
4858 update_status (wait_proc);
4859 if (wait_proc
4860 && ! EQ (wait_proc->status, Qrun)
4861 && ! EQ (wait_proc->status, Qconnect))
4862 {
4863 int nread, total_nread = 0;
4864
4865 clear_waiting_for_input ();
4866 XSETPROCESS (proc, wait_proc);
4867
4868 /* Read data from the process, until we exhaust it. */
4869 while (wait_proc->infd >= 0)
4870 {
4871 nread = read_process_output (proc, wait_proc->infd);
4872
4873 if (nread == 0)
4874 break;
4875
4876 if (0 < nread)
4877 {
4878 total_nread += nread;
4879 got_some_input = 1;
4880 }
4881 #ifdef EIO
4882 else if (nread == -1 && EIO == errno)
4883 break;
4884 #endif
4885 #ifdef EAGAIN
4886 else if (nread == -1 && EAGAIN == errno)
4887 break;
4888 #endif
4889 #ifdef EWOULDBLOCK
4890 else if (nread == -1 && EWOULDBLOCK == errno)
4891 break;
4892 #endif
4893 }
4894 if (total_nread > 0 && do_display)
4895 redisplay_preserve_echo_area (10);
4896
4897 break;
4898 }
4899
4900 /* Wait till there is something to do */
4901
4902 if (wait_proc && just_wait_proc)
4903 {
4904 if (wait_proc->infd < 0) /* Terminated */
4905 break;
4906 FD_SET (wait_proc->infd, &Available);
4907 check_delay = 0;
4908 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4909 }
4910 else if (!NILP (wait_for_cell))
4911 {
4912 Available = non_process_wait_mask;
4913 check_delay = 0;
4914 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4915 }
4916 else
4917 {
4918 if (! read_kbd)
4919 Available = non_keyboard_wait_mask;
4920 else
4921 Available = input_wait_mask;
4922 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4923 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4924 }
4925
4926 /* If frame size has changed or the window is newly mapped,
4927 redisplay now, before we start to wait. There is a race
4928 condition here; if a SIGIO arrives between now and the select
4929 and indicates that a frame is trashed, the select may block
4930 displaying a trashed screen. */
4931 if (frame_garbaged && do_display)
4932 {
4933 clear_waiting_for_input ();
4934 redisplay_preserve_echo_area (11);
4935 if (read_kbd < 0)
4936 set_waiting_for_input (&timeout);
4937 }
4938
4939 no_avail = 0;
4940 if (read_kbd && detect_input_pending ())
4941 {
4942 nfds = 0;
4943 no_avail = 1;
4944 }
4945 else
4946 {
4947 #ifdef NON_BLOCKING_CONNECT
4948 if (check_connect)
4949 Connecting = connect_wait_mask;
4950 #endif
4951
4952 #ifdef ADAPTIVE_READ_BUFFERING
4953 /* Set the timeout for adaptive read buffering if any
4954 process has non-zero read_output_skip and non-zero
4955 read_output_delay, and we are not reading output for a
4956 specific wait_channel. It is not executed if
4957 Vprocess_adaptive_read_buffering is nil. */
4958 if (process_output_skip && check_delay > 0)
4959 {
4960 int usecs = EMACS_USECS (timeout);
4961 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4962 usecs = READ_OUTPUT_DELAY_MAX;
4963 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4964 {
4965 proc = chan_process[channel];
4966 if (NILP (proc))
4967 continue;
4968 /* Find minimum non-zero read_output_delay among the
4969 processes with non-zero read_output_skip. */
4970 if (XPROCESS (proc)->read_output_delay > 0)
4971 {
4972 check_delay--;
4973 if (!XPROCESS (proc)->read_output_skip)
4974 continue;
4975 FD_CLR (channel, &Available);
4976 XPROCESS (proc)->read_output_skip = 0;
4977 if (XPROCESS (proc)->read_output_delay < usecs)
4978 usecs = XPROCESS (proc)->read_output_delay;
4979 }
4980 }
4981 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4982 process_output_skip = 0;
4983 }
4984 #endif
4985 #if defined (USE_GTK) || defined (HAVE_GCONF)
4986 nfds = xg_select
4987 #elif defined (HAVE_NS)
4988 nfds = ns_select
4989 #else
4990 nfds = select
4991 #endif
4992 (max (max (max_process_desc, max_keyboard_desc),
4993 max_gpm_desc) + 1,
4994 &Available,
4995 #ifdef NON_BLOCKING_CONNECT
4996 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4997 #else
4998 (SELECT_TYPE *)0,
4999 #endif
5000 (SELECT_TYPE *)0, &timeout);
5001 }
5002
5003 xerrno = errno;
5004
5005 /* Make C-g and alarm signals set flags again */
5006 clear_waiting_for_input ();
5007
5008 /* If we woke up due to SIGWINCH, actually change size now. */
5009 do_pending_window_change (0);
5010
5011 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
5012 /* We wanted the full specified time, so return now. */
5013 break;
5014 if (nfds < 0)
5015 {
5016 if (xerrno == EINTR)
5017 no_avail = 1;
5018 else if (xerrno == EBADF)
5019 {
5020 #ifdef AIX
5021 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
5022 the child's closure of the pts gives the parent a SIGHUP, and
5023 the ptc file descriptor is automatically closed,
5024 yielding EBADF here or at select() call above.
5025 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
5026 in m/ibmrt-aix.h), and here we just ignore the select error.
5027 Cleanup occurs c/o status_notify after SIGCLD. */
5028 no_avail = 1; /* Cannot depend on values returned */
5029 #else
5030 abort ();
5031 #endif
5032 }
5033 else
5034 error ("select error: %s", emacs_strerror (xerrno));
5035 }
5036
5037 if (no_avail)
5038 {
5039 FD_ZERO (&Available);
5040 IF_NON_BLOCKING_CONNECT (check_connect = 0);
5041 }
5042
5043 #if 0 /* When polling is used, interrupt_input is 0,
5044 so get_input_pending should read the input.
5045 So this should not be needed. */
5046 /* If we are using polling for input,
5047 and we see input available, make it get read now.
5048 Otherwise it might not actually get read for a second.
5049 And on hpux, since we turn off polling in wait_reading_process_output,
5050 it might never get read at all if we don't spend much time
5051 outside of wait_reading_process_output. */
5052 if (read_kbd && interrupt_input
5053 && keyboard_bit_set (&Available)
5054 && input_polling_used ())
5055 kill (getpid (), SIGALRM);
5056 #endif
5057
5058 /* Check for keyboard input */
5059 /* If there is any, return immediately
5060 to give it higher priority than subprocesses */
5061
5062 if (read_kbd != 0)
5063 {
5064 int old_timers_run = timers_run;
5065 struct buffer *old_buffer = current_buffer;
5066 Lisp_Object old_window = selected_window;
5067 int leave = 0;
5068
5069 if (detect_input_pending_run_timers (do_display))
5070 {
5071 swallow_events (do_display);
5072 if (detect_input_pending_run_timers (do_display))
5073 leave = 1;
5074 }
5075
5076 /* If a timer has run, this might have changed buffers
5077 an alike. Make read_key_sequence aware of that. */
5078 if (timers_run != old_timers_run
5079 && waiting_for_user_input_p == -1
5080 && (old_buffer != current_buffer
5081 || !EQ (old_window, selected_window)))
5082 record_asynch_buffer_change ();
5083
5084 if (leave)
5085 break;
5086 }
5087
5088 /* If there is unread keyboard input, also return. */
5089 if (read_kbd != 0
5090 && requeued_events_pending_p ())
5091 break;
5092
5093 /* If we are not checking for keyboard input now,
5094 do process events (but don't run any timers).
5095 This is so that X events will be processed.
5096 Otherwise they may have to wait until polling takes place.
5097 That would causes delays in pasting selections, for example.
5098
5099 (We used to do this only if wait_for_cell.) */
5100 if (read_kbd == 0 && detect_input_pending ())
5101 {
5102 swallow_events (do_display);
5103 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
5104 if (detect_input_pending ())
5105 break;
5106 #endif
5107 }
5108
5109 /* Exit now if the cell we're waiting for became non-nil. */
5110 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
5111 break;
5112
5113 #ifdef SIGIO
5114 /* If we think we have keyboard input waiting, but didn't get SIGIO,
5115 go read it. This can happen with X on BSD after logging out.
5116 In that case, there really is no input and no SIGIO,
5117 but select says there is input. */
5118
5119 if (read_kbd && interrupt_input
5120 && keyboard_bit_set (&Available) && ! noninteractive)
5121 kill (getpid (), SIGIO);
5122 #endif
5123
5124 if (! wait_proc)
5125 got_some_input |= nfds > 0;
5126
5127 /* If checking input just got us a size-change event from X,
5128 obey it now if we should. */
5129 if (read_kbd || ! NILP (wait_for_cell))
5130 do_pending_window_change (0);
5131
5132 /* Check for data from a process. */
5133 if (no_avail || nfds == 0)
5134 continue;
5135
5136 /* Really FIRST_PROC_DESC should be 0 on Unix,
5137 but this is safer in the short run. */
5138 for (channel = 0; channel <= max_process_desc; channel++)
5139 {
5140 if (FD_ISSET (channel, &Available)
5141 && FD_ISSET (channel, &non_keyboard_wait_mask))
5142 {
5143 int nread;
5144
5145 /* If waiting for this channel, arrange to return as
5146 soon as no more input to be processed. No more
5147 waiting. */
5148 if (wait_channel == channel)
5149 {
5150 wait_channel = -1;
5151 time_limit = -1;
5152 got_some_input = 1;
5153 }
5154 proc = chan_process[channel];
5155 if (NILP (proc))
5156 continue;
5157
5158 /* If this is a server stream socket, accept connection. */
5159 if (EQ (XPROCESS (proc)->status, Qlisten))
5160 {
5161 server_accept_connection (proc, channel);
5162 continue;
5163 }
5164
5165 /* Read data from the process, starting with our
5166 buffered-ahead character if we have one. */
5167
5168 nread = read_process_output (proc, channel);
5169 if (nread > 0)
5170 {
5171 /* Since read_process_output can run a filter,
5172 which can call accept-process-output,
5173 don't try to read from any other processes
5174 before doing the select again. */
5175 FD_ZERO (&Available);
5176
5177 if (do_display)
5178 redisplay_preserve_echo_area (12);
5179 }
5180 #ifdef EWOULDBLOCK
5181 else if (nread == -1 && errno == EWOULDBLOCK)
5182 ;
5183 #endif
5184 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5185 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5186 #ifdef O_NONBLOCK
5187 else if (nread == -1 && errno == EAGAIN)
5188 ;
5189 #else
5190 #ifdef O_NDELAY
5191 else if (nread == -1 && errno == EAGAIN)
5192 ;
5193 /* Note that we cannot distinguish between no input
5194 available now and a closed pipe.
5195 With luck, a closed pipe will be accompanied by
5196 subprocess termination and SIGCHLD. */
5197 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5198 ;
5199 #endif /* O_NDELAY */
5200 #endif /* O_NONBLOCK */
5201 #ifdef HAVE_PTYS
5202 /* On some OSs with ptys, when the process on one end of
5203 a pty exits, the other end gets an error reading with
5204 errno = EIO instead of getting an EOF (0 bytes read).
5205 Therefore, if we get an error reading and errno =
5206 EIO, just continue, because the child process has
5207 exited and should clean itself up soon (e.g. when we
5208 get a SIGCHLD).
5209
5210 However, it has been known to happen that the SIGCHLD
5211 got lost. So raise the signal again just in case.
5212 It can't hurt. */
5213 else if (nread == -1 && errno == EIO)
5214 {
5215 /* Clear the descriptor now, so we only raise the
5216 signal once. Don't do this if `process' is only
5217 a pty. */
5218 if (XPROCESS (proc)->pid != -2)
5219 {
5220 FD_CLR (channel, &input_wait_mask);
5221 FD_CLR (channel, &non_keyboard_wait_mask);
5222
5223 kill (getpid (), SIGCHLD);
5224 }
5225 }
5226 #endif /* HAVE_PTYS */
5227 /* If we can detect process termination, don't consider the process
5228 gone just because its pipe is closed. */
5229 #ifdef SIGCHLD
5230 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5231 ;
5232 #endif
5233 else
5234 {
5235 /* Preserve status of processes already terminated. */
5236 XPROCESS (proc)->tick = ++process_tick;
5237 deactivate_process (proc);
5238 if (XPROCESS (proc)->raw_status_new)
5239 update_status (XPROCESS (proc));
5240 if (EQ (XPROCESS (proc)->status, Qrun))
5241 XPROCESS (proc)->status
5242 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5243 }
5244 }
5245 #ifdef NON_BLOCKING_CONNECT
5246 if (check_connect && FD_ISSET (channel, &Connecting)
5247 && FD_ISSET (channel, &connect_wait_mask))
5248 {
5249 struct Lisp_Process *p;
5250
5251 FD_CLR (channel, &connect_wait_mask);
5252 if (--num_pending_connects < 0)
5253 abort ();
5254
5255 proc = chan_process[channel];
5256 if (NILP (proc))
5257 continue;
5258
5259 p = XPROCESS (proc);
5260
5261 #ifdef GNU_LINUX
5262 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5263 So only use it on systems where it is known to work. */
5264 {
5265 int xlen = sizeof(xerrno);
5266 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5267 xerrno = errno;
5268 }
5269 #else
5270 {
5271 struct sockaddr pname;
5272 int pnamelen = sizeof(pname);
5273
5274 /* If connection failed, getpeername will fail. */
5275 xerrno = 0;
5276 if (getpeername(channel, &pname, &pnamelen) < 0)
5277 {
5278 /* Obtain connect failure code through error slippage. */
5279 char dummy;
5280 xerrno = errno;
5281 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
5282 xerrno = errno;
5283 }
5284 }
5285 #endif
5286 if (xerrno)
5287 {
5288 p->tick = ++process_tick;
5289 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5290 deactivate_process (proc);
5291 }
5292 else
5293 {
5294 p->status = Qrun;
5295 /* Execute the sentinel here. If we had relied on
5296 status_notify to do it later, it will read input
5297 from the process before calling the sentinel. */
5298 exec_sentinel (proc, build_string ("open\n"));
5299 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5300 {
5301 FD_SET (p->infd, &input_wait_mask);
5302 FD_SET (p->infd, &non_keyboard_wait_mask);
5303 }
5304 }
5305 }
5306 #endif /* NON_BLOCKING_CONNECT */
5307 } /* end for each file descriptor */
5308 } /* end while exit conditions not met */
5309
5310 unbind_to (count, Qnil);
5311
5312 /* If calling from keyboard input, do not quit
5313 since we want to return C-g as an input character.
5314 Otherwise, do pending quit if requested. */
5315 if (read_kbd >= 0)
5316 {
5317 /* Prevent input_pending from remaining set if we quit. */
5318 clear_input_pending ();
5319 QUIT;
5320 }
5321
5322 return got_some_input;
5323 }
5324 \f
5325 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5326
5327 static Lisp_Object
5328 read_process_output_call (fun_and_args)
5329 Lisp_Object fun_and_args;
5330 {
5331 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5332 }
5333
5334 static Lisp_Object
5335 read_process_output_error_handler (error)
5336 Lisp_Object error;
5337 {
5338 cmd_error_internal (error, "error in process filter: ");
5339 Vinhibit_quit = Qt;
5340 update_echo_area ();
5341 Fsleep_for (make_number (2), Qnil);
5342 return Qt;
5343 }
5344
5345 /* Read pending output from the process channel,
5346 starting with our buffered-ahead character if we have one.
5347 Yield number of decoded characters read.
5348
5349 This function reads at most 4096 characters.
5350 If you want to read all available subprocess output,
5351 you must call it repeatedly until it returns zero.
5352
5353 The characters read are decoded according to PROC's coding-system
5354 for decoding. */
5355
5356 static int
5357 read_process_output (proc, channel)
5358 Lisp_Object proc;
5359 register int channel;
5360 {
5361 register int nbytes;
5362 char *chars;
5363 register Lisp_Object outstream;
5364 register struct Lisp_Process *p = XPROCESS (proc);
5365 register int opoint;
5366 struct coding_system *coding = proc_decode_coding_system[channel];
5367 int carryover = p->decoding_carryover;
5368 int readmax = 4096;
5369
5370 chars = (char *) alloca (carryover + readmax);
5371 if (carryover)
5372 /* See the comment above. */
5373 bcopy (SDATA (p->decoding_buf), chars, carryover);
5374
5375 #ifdef DATAGRAM_SOCKETS
5376 /* We have a working select, so proc_buffered_char is always -1. */
5377 if (DATAGRAM_CHAN_P (channel))
5378 {
5379 int len = datagram_address[channel].len;
5380 nbytes = recvfrom (channel, chars + carryover, readmax,
5381 0, datagram_address[channel].sa, &len);
5382 }
5383 else
5384 #endif
5385 if (proc_buffered_char[channel] < 0)
5386 {
5387 nbytes = emacs_read (channel, chars + carryover, readmax);
5388 #ifdef ADAPTIVE_READ_BUFFERING
5389 if (nbytes > 0 && p->adaptive_read_buffering)
5390 {
5391 int delay = p->read_output_delay;
5392 if (nbytes < 256)
5393 {
5394 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5395 {
5396 if (delay == 0)
5397 process_output_delay_count++;
5398 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5399 }
5400 }
5401 else if (delay > 0 && (nbytes == readmax))
5402 {
5403 delay -= READ_OUTPUT_DELAY_INCREMENT;
5404 if (delay == 0)
5405 process_output_delay_count--;
5406 }
5407 p->read_output_delay = delay;
5408 if (delay)
5409 {
5410 p->read_output_skip = 1;
5411 process_output_skip = 1;
5412 }
5413 }
5414 #endif
5415 }
5416 else
5417 {
5418 chars[carryover] = proc_buffered_char[channel];
5419 proc_buffered_char[channel] = -1;
5420 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5421 if (nbytes < 0)
5422 nbytes = 1;
5423 else
5424 nbytes = nbytes + 1;
5425 }
5426
5427 p->decoding_carryover = 0;
5428
5429 /* At this point, NBYTES holds number of bytes just received
5430 (including the one in proc_buffered_char[channel]). */
5431 if (nbytes <= 0)
5432 {
5433 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5434 return nbytes;
5435 coding->mode |= CODING_MODE_LAST_BLOCK;
5436 }
5437
5438 /* Now set NBYTES how many bytes we must decode. */
5439 nbytes += carryover;
5440
5441 /* Read and dispose of the process output. */
5442 outstream = p->filter;
5443 if (!NILP (outstream))
5444 {
5445 /* We inhibit quit here instead of just catching it so that
5446 hitting ^G when a filter happens to be running won't screw
5447 it up. */
5448 int count = SPECPDL_INDEX ();
5449 Lisp_Object odeactivate;
5450 Lisp_Object obuffer, okeymap;
5451 Lisp_Object text;
5452 int outer_running_asynch_code = running_asynch_code;
5453 int waiting = waiting_for_user_input_p;
5454
5455 /* No need to gcpro these, because all we do with them later
5456 is test them for EQness, and none of them should be a string. */
5457 odeactivate = Vdeactivate_mark;
5458 XSETBUFFER (obuffer, current_buffer);
5459 okeymap = current_buffer->keymap;
5460
5461 specbind (Qinhibit_quit, Qt);
5462 specbind (Qlast_nonmenu_event, Qt);
5463
5464 /* In case we get recursively called,
5465 and we already saved the match data nonrecursively,
5466 save the same match data in safely recursive fashion. */
5467 if (outer_running_asynch_code)
5468 {
5469 Lisp_Object tem;
5470 /* Don't clobber the CURRENT match data, either! */
5471 tem = Fmatch_data (Qnil, Qnil, Qnil);
5472 restore_search_regs ();
5473 record_unwind_save_match_data ();
5474 Fset_match_data (tem, Qt);
5475 }
5476
5477 /* For speed, if a search happens within this code,
5478 save the match data in a special nonrecursive fashion. */
5479 running_asynch_code = 1;
5480
5481 decode_coding_c_string (coding, chars, nbytes, Qt);
5482 text = coding->dst_object;
5483 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5484 /* A new coding system might be found. */
5485 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5486 {
5487 p->decode_coding_system = Vlast_coding_system_used;
5488
5489 /* Don't call setup_coding_system for
5490 proc_decode_coding_system[channel] here. It is done in
5491 detect_coding called via decode_coding above. */
5492
5493 /* If a coding system for encoding is not yet decided, we set
5494 it as the same as coding-system for decoding.
5495
5496 But, before doing that we must check if
5497 proc_encode_coding_system[p->outfd] surely points to a
5498 valid memory because p->outfd will be changed once EOF is
5499 sent to the process. */
5500 if (NILP (p->encode_coding_system)
5501 && proc_encode_coding_system[p->outfd])
5502 {
5503 p->encode_coding_system
5504 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5505 setup_coding_system (p->encode_coding_system,
5506 proc_encode_coding_system[p->outfd]);
5507 }
5508 }
5509
5510 if (coding->carryover_bytes > 0)
5511 {
5512 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5513 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5514 bcopy (coding->carryover, SDATA (p->decoding_buf),
5515 coding->carryover_bytes);
5516 p->decoding_carryover = coding->carryover_bytes;
5517 }
5518 if (SBYTES (text) > 0)
5519 internal_condition_case_1 (read_process_output_call,
5520 Fcons (outstream,
5521 Fcons (proc, Fcons (text, Qnil))),
5522 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5523 read_process_output_error_handler);
5524
5525 /* If we saved the match data nonrecursively, restore it now. */
5526 restore_search_regs ();
5527 running_asynch_code = outer_running_asynch_code;
5528
5529 /* Handling the process output should not deactivate the mark. */
5530 Vdeactivate_mark = odeactivate;
5531
5532 /* Restore waiting_for_user_input_p as it was
5533 when we were called, in case the filter clobbered it. */
5534 waiting_for_user_input_p = waiting;
5535
5536 #if 0 /* Call record_asynch_buffer_change unconditionally,
5537 because we might have changed minor modes or other things
5538 that affect key bindings. */
5539 if (! EQ (Fcurrent_buffer (), obuffer)
5540 || ! EQ (current_buffer->keymap, okeymap))
5541 #endif
5542 /* But do it only if the caller is actually going to read events.
5543 Otherwise there's no need to make him wake up, and it could
5544 cause trouble (for example it would make sit_for return). */
5545 if (waiting_for_user_input_p == -1)
5546 record_asynch_buffer_change ();
5547
5548 unbind_to (count, Qnil);
5549 return nbytes;
5550 }
5551
5552 /* If no filter, write into buffer if it isn't dead. */
5553 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5554 {
5555 Lisp_Object old_read_only;
5556 int old_begv, old_zv;
5557 int old_begv_byte, old_zv_byte;
5558 Lisp_Object odeactivate;
5559 int before, before_byte;
5560 int opoint_byte;
5561 Lisp_Object text;
5562 struct buffer *b;
5563 int count = SPECPDL_INDEX ();
5564
5565 odeactivate = Vdeactivate_mark;
5566
5567 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
5568 Fset_buffer (p->buffer);
5569 opoint = PT;
5570 opoint_byte = PT_BYTE;
5571 old_read_only = current_buffer->read_only;
5572 old_begv = BEGV;
5573 old_zv = ZV;
5574 old_begv_byte = BEGV_BYTE;
5575 old_zv_byte = ZV_BYTE;
5576
5577 current_buffer->read_only = Qnil;
5578
5579 /* Insert new output into buffer
5580 at the current end-of-output marker,
5581 thus preserving logical ordering of input and output. */
5582 if (XMARKER (p->mark)->buffer)
5583 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5584 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5585 ZV_BYTE));
5586 else
5587 SET_PT_BOTH (ZV, ZV_BYTE);
5588 before = PT;
5589 before_byte = PT_BYTE;
5590
5591 /* If the output marker is outside of the visible region, save
5592 the restriction and widen. */
5593 if (! (BEGV <= PT && PT <= ZV))
5594 Fwiden ();
5595
5596 decode_coding_c_string (coding, chars, nbytes, Qt);
5597 text = coding->dst_object;
5598 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5599 /* A new coding system might be found. See the comment in the
5600 similar code in the previous `if' block. */
5601 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5602 {
5603 p->decode_coding_system = Vlast_coding_system_used;
5604 if (NILP (p->encode_coding_system)
5605 && proc_encode_coding_system[p->outfd])
5606 {
5607 p->encode_coding_system
5608 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5609 setup_coding_system (p->encode_coding_system,
5610 proc_encode_coding_system[p->outfd]);
5611 }
5612 }
5613 if (coding->carryover_bytes > 0)
5614 {
5615 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5616 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5617 bcopy (coding->carryover, SDATA (p->decoding_buf),
5618 coding->carryover_bytes);
5619 p->decoding_carryover = coding->carryover_bytes;
5620 }
5621 /* Adjust the multibyteness of TEXT to that of the buffer. */
5622 if (NILP (current_buffer->enable_multibyte_characters)
5623 != ! STRING_MULTIBYTE (text))
5624 text = (STRING_MULTIBYTE (text)
5625 ? Fstring_as_unibyte (text)
5626 : Fstring_to_multibyte (text));
5627 /* Insert before markers in case we are inserting where
5628 the buffer's mark is, and the user's next command is Meta-y. */
5629 insert_from_string_before_markers (text, 0, 0,
5630 SCHARS (text), SBYTES (text), 0);
5631
5632 /* Make sure the process marker's position is valid when the
5633 process buffer is changed in the signal_after_change above.
5634 W3 is known to do that. */
5635 if (BUFFERP (p->buffer)
5636 && (b = XBUFFER (p->buffer), b != current_buffer))
5637 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5638 else
5639 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5640
5641 update_mode_lines++;
5642
5643 /* Make sure opoint and the old restrictions
5644 float ahead of any new text just as point would. */
5645 if (opoint >= before)
5646 {
5647 opoint += PT - before;
5648 opoint_byte += PT_BYTE - before_byte;
5649 }
5650 if (old_begv > before)
5651 {
5652 old_begv += PT - before;
5653 old_begv_byte += PT_BYTE - before_byte;
5654 }
5655 if (old_zv >= before)
5656 {
5657 old_zv += PT - before;
5658 old_zv_byte += PT_BYTE - before_byte;
5659 }
5660
5661 /* If the restriction isn't what it should be, set it. */
5662 if (old_begv != BEGV || old_zv != ZV)
5663 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5664
5665 /* Handling the process output should not deactivate the mark. */
5666 Vdeactivate_mark = odeactivate;
5667
5668 current_buffer->read_only = old_read_only;
5669 SET_PT_BOTH (opoint, opoint_byte);
5670 unbind_to (count, Qnil);
5671 }
5672 return nbytes;
5673 }
5674
5675 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5676 0, 0, 0,
5677 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5678 This is intended for use by asynchronous process output filters and sentinels. */)
5679 ()
5680 {
5681 return (waiting_for_user_input_p ? Qt : Qnil);
5682 }
5683 \f
5684 /* Sending data to subprocess */
5685
5686 jmp_buf send_process_frame;
5687 Lisp_Object process_sent_to;
5688
5689 SIGTYPE
5690 send_process_trap ()
5691 {
5692 SIGNAL_THREAD_CHECK (SIGPIPE);
5693 sigunblock (sigmask (SIGPIPE));
5694 longjmp (send_process_frame, 1);
5695 }
5696
5697 /* Send some data to process PROC.
5698 BUF is the beginning of the data; LEN is the number of characters.
5699 OBJECT is the Lisp object that the data comes from. If OBJECT is
5700 nil or t, it means that the data comes from C string.
5701
5702 If OBJECT is not nil, the data is encoded by PROC's coding-system
5703 for encoding before it is sent.
5704
5705 This function can evaluate Lisp code and can garbage collect. */
5706
5707 static void
5708 send_process (proc, buf, len, object)
5709 volatile Lisp_Object proc;
5710 unsigned char *volatile buf;
5711 volatile int len;
5712 volatile Lisp_Object object;
5713 {
5714 /* Use volatile to protect variables from being clobbered by longjmp. */
5715 struct Lisp_Process *p = XPROCESS (proc);
5716 int rv;
5717 struct coding_system *coding;
5718 struct gcpro gcpro1;
5719 SIGTYPE (*volatile old_sigpipe) ();
5720
5721 GCPRO1 (object);
5722
5723 if (p->raw_status_new)
5724 update_status (p);
5725 if (! EQ (p->status, Qrun))
5726 error ("Process %s not running", SDATA (p->name));
5727 if (p->outfd < 0)
5728 error ("Output file descriptor of %s is closed", SDATA (p->name));
5729
5730 coding = proc_encode_coding_system[p->outfd];
5731 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5732
5733 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5734 || (BUFFERP (object)
5735 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5736 || EQ (object, Qt))
5737 {
5738 p->encode_coding_system
5739 = complement_process_encoding_system (p->encode_coding_system);
5740 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5741 {
5742 /* The coding system for encoding was changed to raw-text
5743 because we sent a unibyte text previously. Now we are
5744 sending a multibyte text, thus we must encode it by the
5745 original coding system specified for the current process.
5746
5747 Another reason we comming here is that the coding system
5748 was just complemented and new one was returned by
5749 complement_process_encoding_system. */
5750 setup_coding_system (p->encode_coding_system, coding);
5751 Vlast_coding_system_used = p->encode_coding_system;
5752 }
5753 coding->src_multibyte = 1;
5754 }
5755 else
5756 {
5757 /* For sending a unibyte text, character code conversion should
5758 not take place but EOL conversion should. So, setup raw-text
5759 or one of the subsidiary if we have not yet done it. */
5760 if (CODING_REQUIRE_ENCODING (coding))
5761 {
5762 if (CODING_REQUIRE_FLUSHING (coding))
5763 {
5764 /* But, before changing the coding, we must flush out data. */
5765 coding->mode |= CODING_MODE_LAST_BLOCK;
5766 send_process (proc, "", 0, Qt);
5767 coding->mode &= CODING_MODE_LAST_BLOCK;
5768 }
5769 setup_coding_system (raw_text_coding_system
5770 (Vlast_coding_system_used),
5771 coding);
5772 coding->src_multibyte = 0;
5773 }
5774 }
5775 coding->dst_multibyte = 0;
5776
5777 if (CODING_REQUIRE_ENCODING (coding))
5778 {
5779 coding->dst_object = Qt;
5780 if (BUFFERP (object))
5781 {
5782 int from_byte, from, to;
5783 int save_pt, save_pt_byte;
5784 struct buffer *cur = current_buffer;
5785
5786 set_buffer_internal (XBUFFER (object));
5787 save_pt = PT, save_pt_byte = PT_BYTE;
5788
5789 from_byte = PTR_BYTE_POS (buf);
5790 from = BYTE_TO_CHAR (from_byte);
5791 to = BYTE_TO_CHAR (from_byte + len);
5792 TEMP_SET_PT_BOTH (from, from_byte);
5793 encode_coding_object (coding, object, from, from_byte,
5794 to, from_byte + len, Qt);
5795 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5796 set_buffer_internal (cur);
5797 }
5798 else if (STRINGP (object))
5799 {
5800 encode_coding_object (coding, object, 0, 0, SCHARS (object),
5801 SBYTES (object), Qt);
5802 }
5803 else
5804 {
5805 coding->dst_object = make_unibyte_string (buf, len);
5806 coding->produced = len;
5807 }
5808
5809 len = coding->produced;
5810 object = coding->dst_object;
5811 buf = SDATA (object);
5812 }
5813
5814 if (pty_max_bytes == 0)
5815 {
5816 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5817 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5818 if (pty_max_bytes < 0)
5819 pty_max_bytes = 250;
5820 #else
5821 pty_max_bytes = 250;
5822 #endif
5823 /* Deduct one, to leave space for the eof. */
5824 pty_max_bytes--;
5825 }
5826
5827 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5828 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5829 when returning with longjmp despite being declared volatile. */
5830 if (!setjmp (send_process_frame))
5831 {
5832 process_sent_to = proc;
5833 while (len > 0)
5834 {
5835 int this = len;
5836
5837 /* Decide how much data we can send in one batch.
5838 Long lines need to be split into multiple batches. */
5839 if (p->pty_flag)
5840 {
5841 /* Starting this at zero is always correct when not the first
5842 iteration because the previous iteration ended by sending C-d.
5843 It may not be correct for the first iteration
5844 if a partial line was sent in a separate send_process call.
5845 If that proves worth handling, we need to save linepos
5846 in the process object. */
5847 int linepos = 0;
5848 unsigned char *ptr = (unsigned char *) buf;
5849 unsigned char *end = (unsigned char *) buf + len;
5850
5851 /* Scan through this text for a line that is too long. */
5852 while (ptr != end && linepos < pty_max_bytes)
5853 {
5854 if (*ptr == '\n')
5855 linepos = 0;
5856 else
5857 linepos++;
5858 ptr++;
5859 }
5860 /* If we found one, break the line there
5861 and put in a C-d to force the buffer through. */
5862 this = ptr - buf;
5863 }
5864
5865 /* Send this batch, using one or more write calls. */
5866 while (this > 0)
5867 {
5868 int outfd = p->outfd;
5869 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5870 #ifdef DATAGRAM_SOCKETS
5871 if (DATAGRAM_CHAN_P (outfd))
5872 {
5873 rv = sendto (outfd, (char *) buf, this,
5874 0, datagram_address[outfd].sa,
5875 datagram_address[outfd].len);
5876 if (rv < 0 && errno == EMSGSIZE)
5877 {
5878 signal (SIGPIPE, old_sigpipe);
5879 report_file_error ("sending datagram",
5880 Fcons (proc, Qnil));
5881 }
5882 }
5883 else
5884 #endif
5885 {
5886 rv = emacs_write (outfd, (char *) buf, this);
5887 #ifdef ADAPTIVE_READ_BUFFERING
5888 if (p->read_output_delay > 0
5889 && p->adaptive_read_buffering == 1)
5890 {
5891 p->read_output_delay = 0;
5892 process_output_delay_count--;
5893 p->read_output_skip = 0;
5894 }
5895 #endif
5896 }
5897 signal (SIGPIPE, old_sigpipe);
5898
5899 if (rv < 0)
5900 {
5901 if (0
5902 #ifdef EWOULDBLOCK
5903 || errno == EWOULDBLOCK
5904 #endif
5905 #ifdef EAGAIN
5906 || errno == EAGAIN
5907 #endif
5908 )
5909 /* Buffer is full. Wait, accepting input;
5910 that may allow the program
5911 to finish doing output and read more. */
5912 {
5913 int offset = 0;
5914
5915 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5916 /* A gross hack to work around a bug in FreeBSD.
5917 In the following sequence, read(2) returns
5918 bogus data:
5919
5920 write(2) 1022 bytes
5921 write(2) 954 bytes, get EAGAIN
5922 read(2) 1024 bytes in process_read_output
5923 read(2) 11 bytes in process_read_output
5924
5925 That is, read(2) returns more bytes than have
5926 ever been written successfully. The 1033 bytes
5927 read are the 1022 bytes written successfully
5928 after processing (for example with CRs added if
5929 the terminal is set up that way which it is
5930 here). The same bytes will be seen again in a
5931 later read(2), without the CRs. */
5932
5933 if (errno == EAGAIN)
5934 {
5935 int flags = FWRITE;
5936 ioctl (p->outfd, TIOCFLUSH, &flags);
5937 }
5938 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5939
5940 /* Running filters might relocate buffers or strings.
5941 Arrange to relocate BUF. */
5942 if (BUFFERP (object))
5943 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5944 else if (STRINGP (object))
5945 offset = buf - SDATA (object);
5946
5947 #ifdef EMACS_HAS_USECS
5948 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5949 #else
5950 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5951 #endif
5952
5953 if (BUFFERP (object))
5954 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5955 else if (STRINGP (object))
5956 buf = offset + SDATA (object);
5957
5958 rv = 0;
5959 }
5960 else
5961 /* This is a real error. */
5962 report_file_error ("writing to process", Fcons (proc, Qnil));
5963 }
5964 buf += rv;
5965 len -= rv;
5966 this -= rv;
5967 }
5968
5969 /* If we sent just part of the string, put in an EOF (C-d)
5970 to force it through, before we send the rest. */
5971 if (len > 0)
5972 Fprocess_send_eof (proc);
5973 }
5974 }
5975 else
5976 {
5977 signal (SIGPIPE, old_sigpipe);
5978 proc = process_sent_to;
5979 p = XPROCESS (proc);
5980 p->raw_status_new = 0;
5981 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5982 p->tick = ++process_tick;
5983 deactivate_process (proc);
5984 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5985 }
5986
5987 UNGCPRO;
5988 }
5989
5990 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5991 3, 3, 0,
5992 doc: /* Send current contents of region as input to PROCESS.
5993 PROCESS may be a process, a buffer, the name of a process or buffer, or
5994 nil, indicating the current buffer's process.
5995 Called from program, takes three arguments, PROCESS, START and END.
5996 If the region is more than 500 characters long,
5997 it is sent in several bunches. This may happen even for shorter regions.
5998 Output from processes can arrive in between bunches. */)
5999 (process, start, end)
6000 Lisp_Object process, start, end;
6001 {
6002 Lisp_Object proc;
6003 int start1, end1;
6004
6005 proc = get_process (process);
6006 validate_region (&start, &end);
6007
6008 if (XINT (start) < GPT && XINT (end) > GPT)
6009 move_gap (XINT (start));
6010
6011 start1 = CHAR_TO_BYTE (XINT (start));
6012 end1 = CHAR_TO_BYTE (XINT (end));
6013 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
6014 Fcurrent_buffer ());
6015
6016 return Qnil;
6017 }
6018
6019 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
6020 2, 2, 0,
6021 doc: /* Send PROCESS the contents of STRING as input.
6022 PROCESS may be a process, a buffer, the name of a process or buffer, or
6023 nil, indicating the current buffer's process.
6024 If STRING is more than 500 characters long,
6025 it is sent in several bunches. This may happen even for shorter strings.
6026 Output from processes can arrive in between bunches. */)
6027 (process, string)
6028 Lisp_Object process, string;
6029 {
6030 Lisp_Object proc;
6031 CHECK_STRING (string);
6032 proc = get_process (process);
6033 send_process (proc, SDATA (string),
6034 SBYTES (string), string);
6035 return Qnil;
6036 }
6037 \f
6038 /* Return the foreground process group for the tty/pty that
6039 the process P uses. */
6040 static int
6041 emacs_get_tty_pgrp (p)
6042 struct Lisp_Process *p;
6043 {
6044 int gid = -1;
6045
6046 #ifdef TIOCGPGRP
6047 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
6048 {
6049 int fd;
6050 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
6051 master side. Try the slave side. */
6052 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
6053
6054 if (fd != -1)
6055 {
6056 ioctl (fd, TIOCGPGRP, &gid);
6057 emacs_close (fd);
6058 }
6059 }
6060 #endif /* defined (TIOCGPGRP ) */
6061
6062 return gid;
6063 }
6064
6065 DEFUN ("process-running-child-p", Fprocess_running_child_p,
6066 Sprocess_running_child_p, 0, 1, 0,
6067 doc: /* Return t if PROCESS has given the terminal to a child.
6068 If the operating system does not make it possible to find out,
6069 return t unconditionally. */)
6070 (process)
6071 Lisp_Object process;
6072 {
6073 /* Initialize in case ioctl doesn't exist or gives an error,
6074 in a way that will cause returning t. */
6075 int gid;
6076 Lisp_Object proc;
6077 struct Lisp_Process *p;
6078
6079 proc = get_process (process);
6080 p = XPROCESS (proc);
6081
6082 if (!EQ (p->type, Qreal))
6083 error ("Process %s is not a subprocess",
6084 SDATA (p->name));
6085 if (p->infd < 0)
6086 error ("Process %s is not active",
6087 SDATA (p->name));
6088
6089 gid = emacs_get_tty_pgrp (p);
6090
6091 if (gid == p->pid)
6092 return Qnil;
6093 return Qt;
6094 }
6095 \f
6096 /* send a signal number SIGNO to PROCESS.
6097 If CURRENT_GROUP is t, that means send to the process group
6098 that currently owns the terminal being used to communicate with PROCESS.
6099 This is used for various commands in shell mode.
6100 If CURRENT_GROUP is lambda, that means send to the process group
6101 that currently owns the terminal, but only if it is NOT the shell itself.
6102
6103 If NOMSG is zero, insert signal-announcements into process's buffers
6104 right away.
6105
6106 If we can, we try to signal PROCESS by sending control characters
6107 down the pty. This allows us to signal inferiors who have changed
6108 their uid, for which killpg would return an EPERM error. */
6109
6110 static void
6111 process_send_signal (process, signo, current_group, nomsg)
6112 Lisp_Object process;
6113 int signo;
6114 Lisp_Object current_group;
6115 int nomsg;
6116 {
6117 Lisp_Object proc;
6118 register struct Lisp_Process *p;
6119 int gid;
6120 int no_pgrp = 0;
6121
6122 proc = get_process (process);
6123 p = XPROCESS (proc);
6124
6125 if (!EQ (p->type, Qreal))
6126 error ("Process %s is not a subprocess",
6127 SDATA (p->name));
6128 if (p->infd < 0)
6129 error ("Process %s is not active",
6130 SDATA (p->name));
6131
6132 if (!p->pty_flag)
6133 current_group = Qnil;
6134
6135 /* If we are using pgrps, get a pgrp number and make it negative. */
6136 if (NILP (current_group))
6137 /* Send the signal to the shell's process group. */
6138 gid = p->pid;
6139 else
6140 {
6141 #ifdef SIGNALS_VIA_CHARACTERS
6142 /* If possible, send signals to the entire pgrp
6143 by sending an input character to it. */
6144
6145 /* TERMIOS is the latest and bestest, and seems most likely to
6146 work. If the system has it, use it. */
6147 #ifdef HAVE_TERMIOS
6148 struct termios t;
6149 cc_t *sig_char = NULL;
6150
6151 tcgetattr (p->infd, &t);
6152
6153 switch (signo)
6154 {
6155 case SIGINT:
6156 sig_char = &t.c_cc[VINTR];
6157 break;
6158
6159 case SIGQUIT:
6160 sig_char = &t.c_cc[VQUIT];
6161 break;
6162
6163 case SIGTSTP:
6164 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
6165 sig_char = &t.c_cc[VSWTCH];
6166 #else
6167 sig_char = &t.c_cc[VSUSP];
6168 #endif
6169 break;
6170 }
6171
6172 if (sig_char && *sig_char != CDISABLE)
6173 {
6174 send_process (proc, sig_char, 1, Qnil);
6175 return;
6176 }
6177 /* If we can't send the signal with a character,
6178 fall through and send it another way. */
6179 #else /* ! HAVE_TERMIOS */
6180
6181 /* On Berkeley descendants, the following IOCTL's retrieve the
6182 current control characters. */
6183 #if defined (TIOCGLTC) && defined (TIOCGETC)
6184
6185 struct tchars c;
6186 struct ltchars lc;
6187
6188 switch (signo)
6189 {
6190 case SIGINT:
6191 ioctl (p->infd, TIOCGETC, &c);
6192 send_process (proc, &c.t_intrc, 1, Qnil);
6193 return;
6194 case SIGQUIT:
6195 ioctl (p->infd, TIOCGETC, &c);
6196 send_process (proc, &c.t_quitc, 1, Qnil);
6197 return;
6198 #ifdef SIGTSTP
6199 case SIGTSTP:
6200 ioctl (p->infd, TIOCGLTC, &lc);
6201 send_process (proc, &lc.t_suspc, 1, Qnil);
6202 return;
6203 #endif /* ! defined (SIGTSTP) */
6204 }
6205
6206 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6207
6208 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6209 characters. */
6210 #ifdef TCGETA
6211 struct termio t;
6212 switch (signo)
6213 {
6214 case SIGINT:
6215 ioctl (p->infd, TCGETA, &t);
6216 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6217 return;
6218 case SIGQUIT:
6219 ioctl (p->infd, TCGETA, &t);
6220 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6221 return;
6222 #ifdef SIGTSTP
6223 case SIGTSTP:
6224 ioctl (p->infd, TCGETA, &t);
6225 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6226 return;
6227 #endif /* ! defined (SIGTSTP) */
6228 }
6229 #else /* ! defined (TCGETA) */
6230 Your configuration files are messed up.
6231 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6232 you'd better be using one of the alternatives above! */
6233 #endif /* ! defined (TCGETA) */
6234 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6235 /* In this case, the code above should alway return. */
6236 abort ();
6237 #endif /* ! defined HAVE_TERMIOS */
6238
6239 /* The code above may fall through if it can't
6240 handle the signal. */
6241 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6242
6243 #ifdef TIOCGPGRP
6244 /* Get the current pgrp using the tty itself, if we have that.
6245 Otherwise, use the pty to get the pgrp.
6246 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6247 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6248 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6249 His patch indicates that if TIOCGPGRP returns an error, then
6250 we should just assume that p->pid is also the process group id. */
6251
6252 gid = emacs_get_tty_pgrp (p);
6253
6254 if (gid == -1)
6255 /* If we can't get the information, assume
6256 the shell owns the tty. */
6257 gid = p->pid;
6258
6259 /* It is not clear whether anything really can set GID to -1.
6260 Perhaps on some system one of those ioctls can or could do so.
6261 Or perhaps this is vestigial. */
6262 if (gid == -1)
6263 no_pgrp = 1;
6264 #else /* ! defined (TIOCGPGRP ) */
6265 /* Can't select pgrps on this system, so we know that
6266 the child itself heads the pgrp. */
6267 gid = p->pid;
6268 #endif /* ! defined (TIOCGPGRP ) */
6269
6270 /* If current_group is lambda, and the shell owns the terminal,
6271 don't send any signal. */
6272 if (EQ (current_group, Qlambda) && gid == p->pid)
6273 return;
6274 }
6275
6276 switch (signo)
6277 {
6278 #ifdef SIGCONT
6279 case SIGCONT:
6280 p->raw_status_new = 0;
6281 p->status = Qrun;
6282 p->tick = ++process_tick;
6283 if (!nomsg)
6284 {
6285 status_notify (NULL);
6286 redisplay_preserve_echo_area (13);
6287 }
6288 break;
6289 #endif /* ! defined (SIGCONT) */
6290 case SIGINT:
6291 case SIGQUIT:
6292 case SIGKILL:
6293 flush_pending_output (p->infd);
6294 break;
6295 }
6296
6297 /* If we don't have process groups, send the signal to the immediate
6298 subprocess. That isn't really right, but it's better than any
6299 obvious alternative. */
6300 if (no_pgrp)
6301 {
6302 kill (p->pid, signo);
6303 return;
6304 }
6305
6306 /* gid may be a pid, or minus a pgrp's number */
6307 #ifdef TIOCSIGSEND
6308 if (!NILP (current_group))
6309 {
6310 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6311 EMACS_KILLPG (gid, signo);
6312 }
6313 else
6314 {
6315 gid = - p->pid;
6316 kill (gid, signo);
6317 }
6318 #else /* ! defined (TIOCSIGSEND) */
6319 EMACS_KILLPG (gid, signo);
6320 #endif /* ! defined (TIOCSIGSEND) */
6321 }
6322
6323 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6324 doc: /* Interrupt process PROCESS.
6325 PROCESS may be a process, a buffer, or the name of a process or buffer.
6326 No arg or nil means current buffer's process.
6327 Second arg CURRENT-GROUP non-nil means send signal to
6328 the current process-group of the process's controlling terminal
6329 rather than to the process's own process group.
6330 If the process is a shell, this means interrupt current subjob
6331 rather than the shell.
6332
6333 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6334 don't send the signal. */)
6335 (process, current_group)
6336 Lisp_Object process, current_group;
6337 {
6338 process_send_signal (process, SIGINT, current_group, 0);
6339 return process;
6340 }
6341
6342 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6343 doc: /* Kill process PROCESS. May be process or name of one.
6344 See function `interrupt-process' for more details on usage. */)
6345 (process, current_group)
6346 Lisp_Object process, current_group;
6347 {
6348 process_send_signal (process, SIGKILL, current_group, 0);
6349 return process;
6350 }
6351
6352 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6353 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6354 See function `interrupt-process' for more details on usage. */)
6355 (process, current_group)
6356 Lisp_Object process, current_group;
6357 {
6358 process_send_signal (process, SIGQUIT, current_group, 0);
6359 return process;
6360 }
6361
6362 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6363 doc: /* Stop process PROCESS. May be process or name of one.
6364 See function `interrupt-process' for more details on usage.
6365 If PROCESS is a network or serial process, inhibit handling of incoming
6366 traffic. */)
6367 (process, current_group)
6368 Lisp_Object process, current_group;
6369 {
6370 #ifdef HAVE_SOCKETS
6371 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6372 {
6373 struct Lisp_Process *p;
6374
6375 p = XPROCESS (process);
6376 if (NILP (p->command)
6377 && p->infd >= 0)
6378 {
6379 FD_CLR (p->infd, &input_wait_mask);
6380 FD_CLR (p->infd, &non_keyboard_wait_mask);
6381 }
6382 p->command = Qt;
6383 return process;
6384 }
6385 #endif
6386 #ifndef SIGTSTP
6387 error ("No SIGTSTP support");
6388 #else
6389 process_send_signal (process, SIGTSTP, current_group, 0);
6390 #endif
6391 return process;
6392 }
6393
6394 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6395 doc: /* Continue process PROCESS. May be process or name of one.
6396 See function `interrupt-process' for more details on usage.
6397 If PROCESS is a network or serial process, resume handling of incoming
6398 traffic. */)
6399 (process, current_group)
6400 Lisp_Object process, current_group;
6401 {
6402 #ifdef HAVE_SOCKETS
6403 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6404 {
6405 struct Lisp_Process *p;
6406
6407 p = XPROCESS (process);
6408 if (EQ (p->command, Qt)
6409 && p->infd >= 0
6410 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6411 {
6412 FD_SET (p->infd, &input_wait_mask);
6413 FD_SET (p->infd, &non_keyboard_wait_mask);
6414 #ifdef WINDOWSNT
6415 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6416 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6417 #endif
6418 #ifdef HAVE_TERMIOS
6419 tcflush (p->infd, TCIFLUSH);
6420 #endif
6421 }
6422 p->command = Qnil;
6423 return process;
6424 }
6425 #endif
6426 #ifdef SIGCONT
6427 process_send_signal (process, SIGCONT, current_group, 0);
6428 #else
6429 error ("No SIGCONT support");
6430 #endif
6431 return process;
6432 }
6433
6434 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6435 2, 2, "sProcess (name or number): \nnSignal code: ",
6436 doc: /* Send PROCESS the signal with code SIGCODE.
6437 PROCESS may also be a number specifying the process id of the
6438 process to signal; in this case, the process need not be a child of
6439 this Emacs.
6440 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6441 (process, sigcode)
6442 Lisp_Object process, sigcode;
6443 {
6444 pid_t pid;
6445
6446 if (INTEGERP (process))
6447 {
6448 pid = XINT (process);
6449 goto got_it;
6450 }
6451
6452 if (FLOATP (process))
6453 {
6454 pid = (pid_t) XFLOAT_DATA (process);
6455 goto got_it;
6456 }
6457
6458 if (STRINGP (process))
6459 {
6460 Lisp_Object tem;
6461 if (tem = Fget_process (process), NILP (tem))
6462 {
6463 pid = XINT (Fstring_to_number (process, make_number (10)));
6464 if (pid > 0)
6465 goto got_it;
6466 }
6467 process = tem;
6468 }
6469 else
6470 process = get_process (process);
6471
6472 if (NILP (process))
6473 return process;
6474
6475 CHECK_PROCESS (process);
6476 pid = XPROCESS (process)->pid;
6477 if (pid <= 0)
6478 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6479
6480 got_it:
6481
6482 #define parse_signal(NAME, VALUE) \
6483 else if (!xstrcasecmp (name, NAME)) \
6484 XSETINT (sigcode, VALUE)
6485
6486 if (INTEGERP (sigcode))
6487 ;
6488 else
6489 {
6490 unsigned char *name;
6491
6492 CHECK_SYMBOL (sigcode);
6493 name = SDATA (SYMBOL_NAME (sigcode));
6494
6495 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6496 name += 3;
6497
6498 if (0)
6499 ;
6500 #ifdef SIGUSR1
6501 parse_signal ("usr1", SIGUSR1);
6502 #endif
6503 #ifdef SIGUSR2
6504 parse_signal ("usr2", SIGUSR2);
6505 #endif
6506 #ifdef SIGTERM
6507 parse_signal ("term", SIGTERM);
6508 #endif
6509 #ifdef SIGHUP
6510 parse_signal ("hup", SIGHUP);
6511 #endif
6512 #ifdef SIGINT
6513 parse_signal ("int", SIGINT);
6514 #endif
6515 #ifdef SIGQUIT
6516 parse_signal ("quit", SIGQUIT);
6517 #endif
6518 #ifdef SIGILL
6519 parse_signal ("ill", SIGILL);
6520 #endif
6521 #ifdef SIGABRT
6522 parse_signal ("abrt", SIGABRT);
6523 #endif
6524 #ifdef SIGEMT
6525 parse_signal ("emt", SIGEMT);
6526 #endif
6527 #ifdef SIGKILL
6528 parse_signal ("kill", SIGKILL);
6529 #endif
6530 #ifdef SIGFPE
6531 parse_signal ("fpe", SIGFPE);
6532 #endif
6533 #ifdef SIGBUS
6534 parse_signal ("bus", SIGBUS);
6535 #endif
6536 #ifdef SIGSEGV
6537 parse_signal ("segv", SIGSEGV);
6538 #endif
6539 #ifdef SIGSYS
6540 parse_signal ("sys", SIGSYS);
6541 #endif
6542 #ifdef SIGPIPE
6543 parse_signal ("pipe", SIGPIPE);
6544 #endif
6545 #ifdef SIGALRM
6546 parse_signal ("alrm", SIGALRM);
6547 #endif
6548 #ifdef SIGURG
6549 parse_signal ("urg", SIGURG);
6550 #endif
6551 #ifdef SIGSTOP
6552 parse_signal ("stop", SIGSTOP);
6553 #endif
6554 #ifdef SIGTSTP
6555 parse_signal ("tstp", SIGTSTP);
6556 #endif
6557 #ifdef SIGCONT
6558 parse_signal ("cont", SIGCONT);
6559 #endif
6560 #ifdef SIGCHLD
6561 parse_signal ("chld", SIGCHLD);
6562 #endif
6563 #ifdef SIGTTIN
6564 parse_signal ("ttin", SIGTTIN);
6565 #endif
6566 #ifdef SIGTTOU
6567 parse_signal ("ttou", SIGTTOU);
6568 #endif
6569 #ifdef SIGIO
6570 parse_signal ("io", SIGIO);
6571 #endif
6572 #ifdef SIGXCPU
6573 parse_signal ("xcpu", SIGXCPU);
6574 #endif
6575 #ifdef SIGXFSZ
6576 parse_signal ("xfsz", SIGXFSZ);
6577 #endif
6578 #ifdef SIGVTALRM
6579 parse_signal ("vtalrm", SIGVTALRM);
6580 #endif
6581 #ifdef SIGPROF
6582 parse_signal ("prof", SIGPROF);
6583 #endif
6584 #ifdef SIGWINCH
6585 parse_signal ("winch", SIGWINCH);
6586 #endif
6587 #ifdef SIGINFO
6588 parse_signal ("info", SIGINFO);
6589 #endif
6590 else
6591 error ("Undefined signal name %s", name);
6592 }
6593
6594 #undef parse_signal
6595
6596 return make_number (kill (pid, XINT (sigcode)));
6597 }
6598
6599 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6600 doc: /* Make PROCESS see end-of-file in its input.
6601 EOF comes after any text already sent to it.
6602 PROCESS may be a process, a buffer, the name of a process or buffer, or
6603 nil, indicating the current buffer's process.
6604 If PROCESS is a network connection, or is a process communicating
6605 through a pipe (as opposed to a pty), then you cannot send any more
6606 text to PROCESS after you call this function.
6607 If PROCESS is a serial process, wait until all output written to the
6608 process has been transmitted to the serial port. */)
6609 (process)
6610 Lisp_Object process;
6611 {
6612 Lisp_Object proc;
6613 struct coding_system *coding;
6614
6615 if (DATAGRAM_CONN_P (process))
6616 return process;
6617
6618 proc = get_process (process);
6619 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6620
6621 /* Make sure the process is really alive. */
6622 if (XPROCESS (proc)->raw_status_new)
6623 update_status (XPROCESS (proc));
6624 if (! EQ (XPROCESS (proc)->status, Qrun))
6625 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6626
6627 if (CODING_REQUIRE_FLUSHING (coding))
6628 {
6629 coding->mode |= CODING_MODE_LAST_BLOCK;
6630 send_process (proc, "", 0, Qnil);
6631 }
6632
6633 if (XPROCESS (proc)->pty_flag)
6634 send_process (proc, "\004", 1, Qnil);
6635 else if (EQ (XPROCESS (proc)->type, Qserial))
6636 {
6637 #ifdef HAVE_TERMIOS
6638 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6639 error ("tcdrain() failed: %s", emacs_strerror (errno));
6640 #endif
6641 /* Do nothing on Windows because writes are blocking. */
6642 }
6643 else
6644 {
6645 int old_outfd, new_outfd;
6646
6647 #ifdef HAVE_SHUTDOWN
6648 /* If this is a network connection, or socketpair is used
6649 for communication with the subprocess, call shutdown to cause EOF.
6650 (In some old system, shutdown to socketpair doesn't work.
6651 Then we just can't win.) */
6652 if (EQ (XPROCESS (proc)->type, Qnetwork)
6653 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6654 shutdown (XPROCESS (proc)->outfd, 1);
6655 /* In case of socketpair, outfd == infd, so don't close it. */
6656 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6657 emacs_close (XPROCESS (proc)->outfd);
6658 #else /* not HAVE_SHUTDOWN */
6659 emacs_close (XPROCESS (proc)->outfd);
6660 #endif /* not HAVE_SHUTDOWN */
6661 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6662 if (new_outfd < 0)
6663 abort ();
6664 old_outfd = XPROCESS (proc)->outfd;
6665
6666 if (!proc_encode_coding_system[new_outfd])
6667 proc_encode_coding_system[new_outfd]
6668 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6669 bcopy (proc_encode_coding_system[old_outfd],
6670 proc_encode_coding_system[new_outfd],
6671 sizeof (struct coding_system));
6672 bzero (proc_encode_coding_system[old_outfd],
6673 sizeof (struct coding_system));
6674
6675 XPROCESS (proc)->outfd = new_outfd;
6676 }
6677 return process;
6678 }
6679
6680 /* Kill all processes associated with `buffer'.
6681 If `buffer' is nil, kill all processes */
6682
6683 void
6684 kill_buffer_processes (buffer)
6685 Lisp_Object buffer;
6686 {
6687 Lisp_Object tail, proc;
6688
6689 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6690 {
6691 proc = XCDR (XCAR (tail));
6692 if (PROCESSP (proc)
6693 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6694 {
6695 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6696 Fdelete_process (proc);
6697 else if (XPROCESS (proc)->infd >= 0)
6698 process_send_signal (proc, SIGHUP, Qnil, 1);
6699 }
6700 }
6701 }
6702 \f
6703 /* On receipt of a signal that a child status has changed, loop asking
6704 about children with changed statuses until the system says there
6705 are no more.
6706
6707 All we do is change the status; we do not run sentinels or print
6708 notifications. That is saved for the next time keyboard input is
6709 done, in order to avoid timing errors.
6710
6711 ** WARNING: this can be called during garbage collection.
6712 Therefore, it must not be fooled by the presence of mark bits in
6713 Lisp objects.
6714
6715 ** USG WARNING: Although it is not obvious from the documentation
6716 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6717 signal() before executing at least one wait(), otherwise the
6718 handler will be called again, resulting in an infinite loop. The
6719 relevant portion of the documentation reads "SIGCLD signals will be
6720 queued and the signal-catching function will be continually
6721 reentered until the queue is empty". Invoking signal() causes the
6722 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6723 Inc.
6724
6725 ** Malloc WARNING: This should never call malloc either directly or
6726 indirectly; if it does, that is a bug */
6727
6728 #ifdef SIGCHLD
6729 SIGTYPE
6730 sigchld_handler (signo)
6731 int signo;
6732 {
6733 int old_errno = errno;
6734 Lisp_Object proc;
6735 register struct Lisp_Process *p;
6736 extern EMACS_TIME *input_available_clear_time;
6737
6738 SIGNAL_THREAD_CHECK (signo);
6739
6740 while (1)
6741 {
6742 pid_t pid;
6743 int w;
6744 Lisp_Object tail;
6745
6746 #ifdef WNOHANG
6747 #ifndef WUNTRACED
6748 #define WUNTRACED 0
6749 #endif /* no WUNTRACED */
6750 /* Keep trying to get a status until we get a definitive result. */
6751 do
6752 {
6753 errno = 0;
6754 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6755 }
6756 while (pid < 0 && errno == EINTR);
6757
6758 if (pid <= 0)
6759 {
6760 /* PID == 0 means no processes found, PID == -1 means a real
6761 failure. We have done all our job, so return. */
6762
6763 /* USG systems forget handlers when they are used;
6764 must reestablish each time */
6765 #if defined (USG) && !defined (POSIX_SIGNALS)
6766 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6767 #endif
6768 errno = old_errno;
6769 return;
6770 }
6771 #else
6772 pid = wait (&w);
6773 #endif /* no WNOHANG */
6774
6775 /* Find the process that signaled us, and record its status. */
6776
6777 /* The process can have been deleted by Fdelete_process. */
6778 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6779 {
6780 Lisp_Object xpid = XCAR (tail);
6781 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6782 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6783 {
6784 XSETCAR (tail, Qnil);
6785 goto sigchld_end_of_loop;
6786 }
6787 }
6788
6789 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6790 p = 0;
6791 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6792 {
6793 proc = XCDR (XCAR (tail));
6794 p = XPROCESS (proc);
6795 if (EQ (p->type, Qreal) && p->pid == pid)
6796 break;
6797 p = 0;
6798 }
6799
6800 /* Look for an asynchronous process whose pid hasn't been filled
6801 in yet. */
6802 if (p == 0)
6803 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6804 {
6805 proc = XCDR (XCAR (tail));
6806 p = XPROCESS (proc);
6807 if (p->pid == -1)
6808 break;
6809 p = 0;
6810 }
6811
6812 /* Change the status of the process that was found. */
6813 if (p != 0)
6814 {
6815 int clear_desc_flag = 0;
6816
6817 p->tick = ++process_tick;
6818 p->raw_status = w;
6819 p->raw_status_new = 1;
6820
6821 /* If process has terminated, stop waiting for its output. */
6822 if ((WIFSIGNALED (w) || WIFEXITED (w))
6823 && p->infd >= 0)
6824 clear_desc_flag = 1;
6825
6826 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6827 if (clear_desc_flag)
6828 {
6829 FD_CLR (p->infd, &input_wait_mask);
6830 FD_CLR (p->infd, &non_keyboard_wait_mask);
6831 }
6832
6833 /* Tell wait_reading_process_output that it needs to wake up and
6834 look around. */
6835 if (input_available_clear_time)
6836 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6837 }
6838
6839 /* There was no asynchronous process found for that pid: we have
6840 a synchronous process. */
6841 else
6842 {
6843 synch_process_alive = 0;
6844
6845 /* Report the status of the synchronous process. */
6846 if (WIFEXITED (w))
6847 synch_process_retcode = WRETCODE (w);
6848 else if (WIFSIGNALED (w))
6849 synch_process_termsig = WTERMSIG (w);
6850
6851 /* Tell wait_reading_process_output that it needs to wake up and
6852 look around. */
6853 if (input_available_clear_time)
6854 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6855 }
6856
6857 sigchld_end_of_loop:
6858 ;
6859
6860 /* On some systems, we must return right away.
6861 If any more processes want to signal us, we will
6862 get another signal.
6863 Otherwise (on systems that have WNOHANG), loop around
6864 to use up all the processes that have something to tell us. */
6865 #if (defined WINDOWSNT \
6866 || (defined USG && !defined GNU_LINUX \
6867 && !(defined HPUX && defined WNOHANG)))
6868 #if defined (USG) && ! defined (POSIX_SIGNALS)
6869 signal (signo, sigchld_handler);
6870 #endif
6871 errno = old_errno;
6872 return;
6873 #endif /* USG, but not HPUX with WNOHANG */
6874 }
6875 }
6876 #endif /* SIGCHLD */
6877 \f
6878
6879 static Lisp_Object
6880 exec_sentinel_unwind (data)
6881 Lisp_Object data;
6882 {
6883 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6884 return Qnil;
6885 }
6886
6887 static Lisp_Object
6888 exec_sentinel_error_handler (error)
6889 Lisp_Object error;
6890 {
6891 cmd_error_internal (error, "error in process sentinel: ");
6892 Vinhibit_quit = Qt;
6893 update_echo_area ();
6894 Fsleep_for (make_number (2), Qnil);
6895 return Qt;
6896 }
6897
6898 static void
6899 exec_sentinel (proc, reason)
6900 Lisp_Object proc, reason;
6901 {
6902 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6903 register struct Lisp_Process *p = XPROCESS (proc);
6904 int count = SPECPDL_INDEX ();
6905 int outer_running_asynch_code = running_asynch_code;
6906 int waiting = waiting_for_user_input_p;
6907
6908 if (inhibit_sentinels)
6909 return;
6910
6911 /* No need to gcpro these, because all we do with them later
6912 is test them for EQness, and none of them should be a string. */
6913 odeactivate = Vdeactivate_mark;
6914 XSETBUFFER (obuffer, current_buffer);
6915 okeymap = current_buffer->keymap;
6916
6917 sentinel = p->sentinel;
6918 if (NILP (sentinel))
6919 return;
6920
6921 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6922 assure that it gets restored no matter how the sentinel exits. */
6923 p->sentinel = Qnil;
6924 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6925 /* Inhibit quit so that random quits don't screw up a running filter. */
6926 specbind (Qinhibit_quit, Qt);
6927 specbind (Qlast_nonmenu_event, Qt); /* Why? --Stef */
6928
6929 /* In case we get recursively called,
6930 and we already saved the match data nonrecursively,
6931 save the same match data in safely recursive fashion. */
6932 if (outer_running_asynch_code)
6933 {
6934 Lisp_Object tem;
6935 tem = Fmatch_data (Qnil, Qnil, Qnil);
6936 restore_search_regs ();
6937 record_unwind_save_match_data ();
6938 Fset_match_data (tem, Qt);
6939 }
6940
6941 /* For speed, if a search happens within this code,
6942 save the match data in a special nonrecursive fashion. */
6943 running_asynch_code = 1;
6944
6945 internal_condition_case_1 (read_process_output_call,
6946 Fcons (sentinel,
6947 Fcons (proc, Fcons (reason, Qnil))),
6948 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6949 exec_sentinel_error_handler);
6950
6951 /* If we saved the match data nonrecursively, restore it now. */
6952 restore_search_regs ();
6953 running_asynch_code = outer_running_asynch_code;
6954
6955 Vdeactivate_mark = odeactivate;
6956
6957 /* Restore waiting_for_user_input_p as it was
6958 when we were called, in case the filter clobbered it. */
6959 waiting_for_user_input_p = waiting;
6960
6961 #if 0
6962 if (! EQ (Fcurrent_buffer (), obuffer)
6963 || ! EQ (current_buffer->keymap, okeymap))
6964 #endif
6965 /* But do it only if the caller is actually going to read events.
6966 Otherwise there's no need to make him wake up, and it could
6967 cause trouble (for example it would make sit_for return). */
6968 if (waiting_for_user_input_p == -1)
6969 record_asynch_buffer_change ();
6970
6971 unbind_to (count, Qnil);
6972 }
6973
6974 /* Report all recent events of a change in process status
6975 (either run the sentinel or output a message).
6976 This is usually done while Emacs is waiting for keyboard input
6977 but can be done at other times. */
6978
6979 static void
6980 status_notify (deleting_process)
6981 struct Lisp_Process *deleting_process;
6982 {
6983 register Lisp_Object proc, buffer;
6984 Lisp_Object tail, msg;
6985 struct gcpro gcpro1, gcpro2;
6986
6987 tail = Qnil;
6988 msg = Qnil;
6989 /* We need to gcpro tail; if read_process_output calls a filter
6990 which deletes a process and removes the cons to which tail points
6991 from Vprocess_alist, and then causes a GC, tail is an unprotected
6992 reference. */
6993 GCPRO2 (tail, msg);
6994
6995 /* Set this now, so that if new processes are created by sentinels
6996 that we run, we get called again to handle their status changes. */
6997 update_tick = process_tick;
6998
6999 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
7000 {
7001 Lisp_Object symbol;
7002 register struct Lisp_Process *p;
7003
7004 proc = Fcdr (XCAR (tail));
7005 p = XPROCESS (proc);
7006
7007 if (p->tick != p->update_tick)
7008 {
7009 p->update_tick = p->tick;
7010
7011 /* If process is still active, read any output that remains. */
7012 while (! EQ (p->filter, Qt)
7013 && ! EQ (p->status, Qconnect)
7014 && ! EQ (p->status, Qlisten)
7015 /* Network or serial process not stopped: */
7016 && ! EQ (p->command, Qt)
7017 && p->infd >= 0
7018 && p != deleting_process
7019 && read_process_output (proc, p->infd) > 0);
7020
7021 buffer = p->buffer;
7022
7023 /* Get the text to use for the message. */
7024 if (p->raw_status_new)
7025 update_status (p);
7026 msg = status_message (p);
7027
7028 /* If process is terminated, deactivate it or delete it. */
7029 symbol = p->status;
7030 if (CONSP (p->status))
7031 symbol = XCAR (p->status);
7032
7033 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
7034 || EQ (symbol, Qclosed))
7035 {
7036 if (delete_exited_processes)
7037 remove_process (proc);
7038 else
7039 deactivate_process (proc);
7040 }
7041
7042 /* The actions above may have further incremented p->tick.
7043 So set p->update_tick again
7044 so that an error in the sentinel will not cause
7045 this code to be run again. */
7046 p->update_tick = p->tick;
7047 /* Now output the message suitably. */
7048 if (!NILP (p->sentinel))
7049 exec_sentinel (proc, msg);
7050 /* Don't bother with a message in the buffer
7051 when a process becomes runnable. */
7052 else if (!EQ (symbol, Qrun) && !NILP (buffer))
7053 {
7054 Lisp_Object ro, tem;
7055 struct buffer *old = current_buffer;
7056 int opoint, opoint_byte;
7057 int before, before_byte;
7058
7059 ro = XBUFFER (buffer)->read_only;
7060
7061 /* Avoid error if buffer is deleted
7062 (probably that's why the process is dead, too) */
7063 if (NILP (XBUFFER (buffer)->name))
7064 continue;
7065 Fset_buffer (buffer);
7066
7067 opoint = PT;
7068 opoint_byte = PT_BYTE;
7069 /* Insert new output into buffer
7070 at the current end-of-output marker,
7071 thus preserving logical ordering of input and output. */
7072 if (XMARKER (p->mark)->buffer)
7073 Fgoto_char (p->mark);
7074 else
7075 SET_PT_BOTH (ZV, ZV_BYTE);
7076
7077 before = PT;
7078 before_byte = PT_BYTE;
7079
7080 tem = current_buffer->read_only;
7081 current_buffer->read_only = Qnil;
7082 insert_string ("\nProcess ");
7083 Finsert (1, &p->name);
7084 insert_string (" ");
7085 Finsert (1, &msg);
7086 current_buffer->read_only = tem;
7087 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
7088
7089 if (opoint >= before)
7090 SET_PT_BOTH (opoint + (PT - before),
7091 opoint_byte + (PT_BYTE - before_byte));
7092 else
7093 SET_PT_BOTH (opoint, opoint_byte);
7094
7095 set_buffer_internal (old);
7096 }
7097 }
7098 } /* end for */
7099
7100 update_mode_lines++; /* in case buffers use %s in mode-line-format */
7101 UNGCPRO;
7102 }
7103
7104 \f
7105 DEFUN ("set-process-coding-system", Fset_process_coding_system,
7106 Sset_process_coding_system, 1, 3, 0,
7107 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
7108 DECODING will be used to decode subprocess output and ENCODING to
7109 encode subprocess input. */)
7110 (process, decoding, encoding)
7111 register Lisp_Object process, decoding, encoding;
7112 {
7113 register struct Lisp_Process *p;
7114
7115 CHECK_PROCESS (process);
7116 p = XPROCESS (process);
7117 if (p->infd < 0)
7118 error ("Input file descriptor of %s closed", SDATA (p->name));
7119 if (p->outfd < 0)
7120 error ("Output file descriptor of %s closed", SDATA (p->name));
7121 Fcheck_coding_system (decoding);
7122 Fcheck_coding_system (encoding);
7123 encoding = coding_inherit_eol_type (encoding, Qnil);
7124 p->decode_coding_system = decoding;
7125 p->encode_coding_system = encoding;
7126 setup_process_coding_systems (process);
7127
7128 return Qnil;
7129 }
7130
7131 DEFUN ("process-coding-system",
7132 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
7133 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
7134 (process)
7135 register Lisp_Object process;
7136 {
7137 CHECK_PROCESS (process);
7138 return Fcons (XPROCESS (process)->decode_coding_system,
7139 XPROCESS (process)->encode_coding_system);
7140 }
7141
7142 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
7143 Sset_process_filter_multibyte, 2, 2, 0,
7144 doc: /* Set multibyteness of the strings given to PROCESS's filter.
7145 If FLAG is non-nil, the filter is given multibyte strings.
7146 If FLAG is nil, the filter is given unibyte strings. In this case,
7147 all character code conversion except for end-of-line conversion is
7148 suppressed. */)
7149 (process, flag)
7150 Lisp_Object process, flag;
7151 {
7152 register struct Lisp_Process *p;
7153
7154 CHECK_PROCESS (process);
7155 p = XPROCESS (process);
7156 if (NILP (flag))
7157 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
7158 setup_process_coding_systems (process);
7159
7160 return Qnil;
7161 }
7162
7163 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
7164 Sprocess_filter_multibyte_p, 1, 1, 0,
7165 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
7166 (process)
7167 Lisp_Object process;
7168 {
7169 register struct Lisp_Process *p;
7170 struct coding_system *coding;
7171
7172 CHECK_PROCESS (process);
7173 p = XPROCESS (process);
7174 coding = proc_decode_coding_system[p->infd];
7175 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7176 }
7177
7178
7179 \f
7180 /* Add DESC to the set of keyboard input descriptors. */
7181
7182 void
7183 add_keyboard_wait_descriptor (desc)
7184 int desc;
7185 {
7186 FD_SET (desc, &input_wait_mask);
7187 FD_SET (desc, &non_process_wait_mask);
7188 if (desc > max_keyboard_desc)
7189 max_keyboard_desc = desc;
7190 }
7191
7192 static int add_gpm_wait_descriptor_called_flag;
7193
7194 void
7195 add_gpm_wait_descriptor (desc)
7196 int desc;
7197 {
7198 if (! add_gpm_wait_descriptor_called_flag)
7199 FD_CLR (0, &input_wait_mask);
7200 add_gpm_wait_descriptor_called_flag = 1;
7201 FD_SET (desc, &input_wait_mask);
7202 FD_SET (desc, &gpm_wait_mask);
7203 if (desc > max_gpm_desc)
7204 max_gpm_desc = desc;
7205 }
7206
7207 /* From now on, do not expect DESC to give keyboard input. */
7208
7209 void
7210 delete_keyboard_wait_descriptor (desc)
7211 int desc;
7212 {
7213 int fd;
7214 int lim = max_keyboard_desc;
7215
7216 FD_CLR (desc, &input_wait_mask);
7217 FD_CLR (desc, &non_process_wait_mask);
7218
7219 if (desc == max_keyboard_desc)
7220 for (fd = 0; fd < lim; fd++)
7221 if (FD_ISSET (fd, &input_wait_mask)
7222 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7223 && !FD_ISSET (fd, &gpm_wait_mask))
7224 max_keyboard_desc = fd;
7225 }
7226
7227 void
7228 delete_gpm_wait_descriptor (desc)
7229 int desc;
7230 {
7231 int fd;
7232 int lim = max_gpm_desc;
7233
7234 FD_CLR (desc, &input_wait_mask);
7235 FD_CLR (desc, &non_process_wait_mask);
7236
7237 if (desc == max_gpm_desc)
7238 for (fd = 0; fd < lim; fd++)
7239 if (FD_ISSET (fd, &input_wait_mask)
7240 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7241 && !FD_ISSET (fd, &non_process_wait_mask))
7242 max_gpm_desc = fd;
7243 }
7244
7245 /* Return nonzero if *MASK has a bit set
7246 that corresponds to one of the keyboard input descriptors. */
7247
7248 static int
7249 keyboard_bit_set (mask)
7250 SELECT_TYPE *mask;
7251 {
7252 int fd;
7253
7254 for (fd = 0; fd <= max_keyboard_desc; fd++)
7255 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7256 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7257 return 1;
7258
7259 return 0;
7260 }
7261
7262 /* Stop reading input from keyboard sources. */
7263
7264 void
7265 hold_keyboard_input (void)
7266 {
7267 kbd_is_on_hold = 1;
7268 }
7269
7270 /* Resume reading input from keyboard sources. */
7271
7272 void
7273 unhold_keyboard_input (void)
7274 {
7275 kbd_is_on_hold = 0;
7276 }
7277
7278 /* Return non-zero if keyboard input is on hold, zero otherwise. */
7279
7280 int
7281 kbd_on_hold_p (void)
7282 {
7283 return kbd_is_on_hold;
7284 }
7285
7286 \f
7287 /* Enumeration of and access to system processes a-la ps(1). */
7288
7289 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7290 0, 0, 0,
7291 doc: /* Return a list of numerical process IDs of all running processes.
7292 If this functionality is unsupported, return nil.
7293
7294 See `process-attributes' for getting attributes of a process given its ID. */)
7295 ()
7296 {
7297 return list_system_processes ();
7298 }
7299
7300 DEFUN ("process-attributes", Fprocess_attributes,
7301 Sprocess_attributes, 1, 1, 0,
7302 doc: /* Return attributes of the process given by its PID, a number.
7303
7304 Value is an alist where each element is a cons cell of the form
7305
7306 \(KEY . VALUE)
7307
7308 If this functionality is unsupported, the value is nil.
7309
7310 See `list-system-processes' for getting a list of all process IDs.
7311
7312 The KEYs of the attributes that this function may return are listed
7313 below, together with the type of the associated VALUE (in parentheses).
7314 Not all platforms support all of these attributes; unsupported
7315 attributes will not appear in the returned alist.
7316 Unless explicitly indicated otherwise, numbers can have either
7317 integer or floating point values.
7318
7319 euid -- Effective user User ID of the process (number)
7320 user -- User name corresponding to euid (string)
7321 egid -- Effective user Group ID of the process (number)
7322 group -- Group name corresponding to egid (string)
7323 comm -- Command name (executable name only) (string)
7324 state -- Process state code, such as "S", "R", or "T" (string)
7325 ppid -- Parent process ID (number)
7326 pgrp -- Process group ID (number)
7327 sess -- Session ID, i.e. process ID of session leader (number)
7328 ttname -- Controlling tty name (string)
7329 tpgid -- ID of foreground process group on the process's tty (number)
7330 minflt -- number of minor page faults (number)
7331 majflt -- number of major page faults (number)
7332 cminflt -- cumulative number of minor page faults (number)
7333 cmajflt -- cumulative number of major page faults (number)
7334 utime -- user time used by the process, in the (HIGH LOW USEC) format
7335 stime -- system time used by the process, in the (HIGH LOW USEC) format
7336 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7337 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7338 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7339 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7340 pri -- priority of the process (number)
7341 nice -- nice value of the process (number)
7342 thcount -- process thread count (number)
7343 start -- time the process started, in the (HIGH LOW USEC) format
7344 vsize -- virtual memory size of the process in KB's (number)
7345 rss -- resident set size of the process in KB's (number)
7346 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7347 pcpu -- percents of CPU time used by the process (floating-point number)
7348 pmem -- percents of total physical memory used by process's resident set
7349 (floating-point number)
7350 args -- command line which invoked the process (string). */)
7351 (pid)
7352
7353 Lisp_Object pid;
7354 {
7355 return system_process_attributes (pid);
7356 }
7357 \f
7358 void
7359 init_process ()
7360 {
7361 register int i;
7362
7363 inhibit_sentinels = 0;
7364
7365 #ifdef SIGCHLD
7366 #ifndef CANNOT_DUMP
7367 if (! noninteractive || initialized)
7368 #endif
7369 signal (SIGCHLD, sigchld_handler);
7370 #endif
7371
7372 FD_ZERO (&input_wait_mask);
7373 FD_ZERO (&non_keyboard_wait_mask);
7374 FD_ZERO (&non_process_wait_mask);
7375 max_process_desc = 0;
7376
7377 #ifdef NON_BLOCKING_CONNECT
7378 FD_ZERO (&connect_wait_mask);
7379 num_pending_connects = 0;
7380 #endif
7381
7382 #ifdef ADAPTIVE_READ_BUFFERING
7383 process_output_delay_count = 0;
7384 process_output_skip = 0;
7385 #endif
7386
7387 /* Don't do this, it caused infinite select loops. The display
7388 method should call add_keyboard_wait_descriptor on stdin if it
7389 needs that. */
7390 #if 0
7391 FD_SET (0, &input_wait_mask);
7392 #endif
7393
7394 Vprocess_alist = Qnil;
7395 #ifdef SIGCHLD
7396 deleted_pid_list = Qnil;
7397 #endif
7398 for (i = 0; i < MAXDESC; i++)
7399 {
7400 chan_process[i] = Qnil;
7401 proc_buffered_char[i] = -1;
7402 }
7403 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
7404 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
7405 #ifdef DATAGRAM_SOCKETS
7406 bzero (datagram_address, sizeof datagram_address);
7407 #endif
7408
7409 #ifdef HAVE_SOCKETS
7410 {
7411 Lisp_Object subfeatures = Qnil;
7412 const struct socket_options *sopt;
7413
7414 #define ADD_SUBFEATURE(key, val) \
7415 subfeatures = pure_cons (pure_cons (key, pure_cons (val, Qnil)), subfeatures)
7416
7417 #ifdef NON_BLOCKING_CONNECT
7418 ADD_SUBFEATURE (QCnowait, Qt);
7419 #endif
7420 #ifdef DATAGRAM_SOCKETS
7421 ADD_SUBFEATURE (QCtype, Qdatagram);
7422 #endif
7423 #ifdef HAVE_SEQPACKET
7424 ADD_SUBFEATURE (QCtype, Qseqpacket);
7425 #endif
7426 #ifdef HAVE_LOCAL_SOCKETS
7427 ADD_SUBFEATURE (QCfamily, Qlocal);
7428 #endif
7429 ADD_SUBFEATURE (QCfamily, Qipv4);
7430 #ifdef AF_INET6
7431 ADD_SUBFEATURE (QCfamily, Qipv6);
7432 #endif
7433 #ifdef HAVE_GETSOCKNAME
7434 ADD_SUBFEATURE (QCservice, Qt);
7435 #endif
7436 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7437 ADD_SUBFEATURE (QCserver, Qt);
7438 #endif
7439
7440 for (sopt = socket_options; sopt->name; sopt++)
7441 subfeatures = pure_cons (intern_c_string (sopt->name), subfeatures);
7442
7443 Fprovide (intern_c_string ("make-network-process"), subfeatures);
7444 }
7445 #endif /* HAVE_SOCKETS */
7446
7447 #if defined (DARWIN_OS)
7448 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7449 processes. As such, we only change the default value. */
7450 if (initialized)
7451 {
7452 char *release = get_operating_system_release();
7453 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7454 && release[1] == '.')) {
7455 Vprocess_connection_type = Qnil;
7456 }
7457 }
7458 #endif
7459 }
7460
7461 void
7462 syms_of_process ()
7463 {
7464 Qprocessp = intern_c_string ("processp");
7465 staticpro (&Qprocessp);
7466 Qrun = intern_c_string ("run");
7467 staticpro (&Qrun);
7468 Qstop = intern_c_string ("stop");
7469 staticpro (&Qstop);
7470 Qsignal = intern_c_string ("signal");
7471 staticpro (&Qsignal);
7472
7473 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7474 here again.
7475
7476 Qexit = intern_c_string ("exit");
7477 staticpro (&Qexit); */
7478
7479 Qopen = intern_c_string ("open");
7480 staticpro (&Qopen);
7481 Qclosed = intern_c_string ("closed");
7482 staticpro (&Qclosed);
7483 Qconnect = intern_c_string ("connect");
7484 staticpro (&Qconnect);
7485 Qfailed = intern_c_string ("failed");
7486 staticpro (&Qfailed);
7487 Qlisten = intern_c_string ("listen");
7488 staticpro (&Qlisten);
7489 Qlocal = intern_c_string ("local");
7490 staticpro (&Qlocal);
7491 Qipv4 = intern_c_string ("ipv4");
7492 staticpro (&Qipv4);
7493 #ifdef AF_INET6
7494 Qipv6 = intern_c_string ("ipv6");
7495 staticpro (&Qipv6);
7496 #endif
7497 Qdatagram = intern_c_string ("datagram");
7498 staticpro (&Qdatagram);
7499 Qseqpacket = intern_c_string ("seqpacket");
7500 staticpro (&Qseqpacket);
7501
7502 QCport = intern_c_string (":port");
7503 staticpro (&QCport);
7504 QCspeed = intern_c_string (":speed");
7505 staticpro (&QCspeed);
7506 QCprocess = intern_c_string (":process");
7507 staticpro (&QCprocess);
7508
7509 QCbytesize = intern_c_string (":bytesize");
7510 staticpro (&QCbytesize);
7511 QCstopbits = intern_c_string (":stopbits");
7512 staticpro (&QCstopbits);
7513 QCparity = intern_c_string (":parity");
7514 staticpro (&QCparity);
7515 Qodd = intern_c_string ("odd");
7516 staticpro (&Qodd);
7517 Qeven = intern_c_string ("even");
7518 staticpro (&Qeven);
7519 QCflowcontrol = intern_c_string (":flowcontrol");
7520 staticpro (&QCflowcontrol);
7521 Qhw = intern_c_string ("hw");
7522 staticpro (&Qhw);
7523 Qsw = intern_c_string ("sw");
7524 staticpro (&Qsw);
7525 QCsummary = intern_c_string (":summary");
7526 staticpro (&QCsummary);
7527
7528 Qreal = intern_c_string ("real");
7529 staticpro (&Qreal);
7530 Qnetwork = intern_c_string ("network");
7531 staticpro (&Qnetwork);
7532 Qserial = intern_c_string ("serial");
7533 staticpro (&Qserial);
7534
7535 QCname = intern_c_string (":name");
7536 staticpro (&QCname);
7537 QCbuffer = intern_c_string (":buffer");
7538 staticpro (&QCbuffer);
7539 QChost = intern_c_string (":host");
7540 staticpro (&QChost);
7541 QCservice = intern_c_string (":service");
7542 staticpro (&QCservice);
7543 QCtype = intern_c_string (":type");
7544 staticpro (&QCtype);
7545 QClocal = intern_c_string (":local");
7546 staticpro (&QClocal);
7547 QCremote = intern_c_string (":remote");
7548 staticpro (&QCremote);
7549 QCcoding = intern_c_string (":coding");
7550 staticpro (&QCcoding);
7551 QCserver = intern_c_string (":server");
7552 staticpro (&QCserver);
7553 QCnowait = intern_c_string (":nowait");
7554 staticpro (&QCnowait);
7555 QCsentinel = intern_c_string (":sentinel");
7556 staticpro (&QCsentinel);
7557 QClog = intern_c_string (":log");
7558 staticpro (&QClog);
7559 QCnoquery = intern_c_string (":noquery");
7560 staticpro (&QCnoquery);
7561 QCstop = intern_c_string (":stop");
7562 staticpro (&QCstop);
7563 QCoptions = intern_c_string (":options");
7564 staticpro (&QCoptions);
7565 QCplist = intern_c_string (":plist");
7566 staticpro (&QCplist);
7567
7568 Qlast_nonmenu_event = intern_c_string ("last-nonmenu-event");
7569 staticpro (&Qlast_nonmenu_event);
7570
7571 staticpro (&Vprocess_alist);
7572 #ifdef SIGCHLD
7573 staticpro (&deleted_pid_list);
7574 #endif
7575
7576 Qeuid = intern_c_string ("euid");
7577 staticpro (&Qeuid);
7578 Qegid = intern_c_string ("egid");
7579 staticpro (&Qegid);
7580 Quser = intern_c_string ("user");
7581 staticpro (&Quser);
7582 Qgroup = intern_c_string ("group");
7583 staticpro (&Qgroup);
7584 Qcomm = intern_c_string ("comm");
7585 staticpro (&Qcomm);
7586 Qstate = intern_c_string ("state");
7587 staticpro (&Qstate);
7588 Qppid = intern_c_string ("ppid");
7589 staticpro (&Qppid);
7590 Qpgrp = intern_c_string ("pgrp");
7591 staticpro (&Qpgrp);
7592 Qsess = intern_c_string ("sess");
7593 staticpro (&Qsess);
7594 Qttname = intern_c_string ("ttname");
7595 staticpro (&Qttname);
7596 Qtpgid = intern_c_string ("tpgid");
7597 staticpro (&Qtpgid);
7598 Qminflt = intern_c_string ("minflt");
7599 staticpro (&Qminflt);
7600 Qmajflt = intern_c_string ("majflt");
7601 staticpro (&Qmajflt);
7602 Qcminflt = intern_c_string ("cminflt");
7603 staticpro (&Qcminflt);
7604 Qcmajflt = intern_c_string ("cmajflt");
7605 staticpro (&Qcmajflt);
7606 Qutime = intern_c_string ("utime");
7607 staticpro (&Qutime);
7608 Qstime = intern_c_string ("stime");
7609 staticpro (&Qstime);
7610 Qtime = intern_c_string ("time");
7611 staticpro (&Qtime);
7612 Qcutime = intern_c_string ("cutime");
7613 staticpro (&Qcutime);
7614 Qcstime = intern_c_string ("cstime");
7615 staticpro (&Qcstime);
7616 Qctime = intern_c_string ("ctime");
7617 staticpro (&Qctime);
7618 Qpri = intern_c_string ("pri");
7619 staticpro (&Qpri);
7620 Qnice = intern_c_string ("nice");
7621 staticpro (&Qnice);
7622 Qthcount = intern_c_string ("thcount");
7623 staticpro (&Qthcount);
7624 Qstart = intern_c_string ("start");
7625 staticpro (&Qstart);
7626 Qvsize = intern_c_string ("vsize");
7627 staticpro (&Qvsize);
7628 Qrss = intern_c_string ("rss");
7629 staticpro (&Qrss);
7630 Qetime = intern_c_string ("etime");
7631 staticpro (&Qetime);
7632 Qpcpu = intern_c_string ("pcpu");
7633 staticpro (&Qpcpu);
7634 Qpmem = intern_c_string ("pmem");
7635 staticpro (&Qpmem);
7636 Qargs = intern_c_string ("args");
7637 staticpro (&Qargs);
7638
7639 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7640 doc: /* *Non-nil means delete processes immediately when they exit.
7641 A value of nil means don't delete them until `list-processes' is run. */);
7642
7643 delete_exited_processes = 1;
7644
7645 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7646 doc: /* Control type of device used to communicate with subprocesses.
7647 Values are nil to use a pipe, or t or `pty' to use a pty.
7648 The value has no effect if the system has no ptys or if all ptys are busy:
7649 then a pipe is used in any case.
7650 The value takes effect when `start-process' is called. */);
7651 Vprocess_connection_type = Qt;
7652
7653 #ifdef ADAPTIVE_READ_BUFFERING
7654 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7655 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7656 On some systems, when Emacs reads the output from a subprocess, the output data
7657 is read in very small blocks, potentially resulting in very poor performance.
7658 This behavior can be remedied to some extent by setting this variable to a
7659 non-nil value, as it will automatically delay reading from such processes, to
7660 allow them to produce more output before Emacs tries to read it.
7661 If the value is t, the delay is reset after each write to the process; any other
7662 non-nil value means that the delay is not reset on write.
7663 The variable takes effect when `start-process' is called. */);
7664 Vprocess_adaptive_read_buffering = Qt;
7665 #endif
7666
7667 defsubr (&Sprocessp);
7668 defsubr (&Sget_process);
7669 defsubr (&Sget_buffer_process);
7670 defsubr (&Sdelete_process);
7671 defsubr (&Sprocess_status);
7672 defsubr (&Sprocess_exit_status);
7673 defsubr (&Sprocess_id);
7674 defsubr (&Sprocess_name);
7675 defsubr (&Sprocess_tty_name);
7676 defsubr (&Sprocess_command);
7677 defsubr (&Sset_process_buffer);
7678 defsubr (&Sprocess_buffer);
7679 defsubr (&Sprocess_mark);
7680 defsubr (&Sset_process_filter);
7681 defsubr (&Sprocess_filter);
7682 defsubr (&Sset_process_sentinel);
7683 defsubr (&Sprocess_sentinel);
7684 defsubr (&Sset_process_window_size);
7685 defsubr (&Sset_process_inherit_coding_system_flag);
7686 defsubr (&Sprocess_inherit_coding_system_flag);
7687 defsubr (&Sset_process_query_on_exit_flag);
7688 defsubr (&Sprocess_query_on_exit_flag);
7689 defsubr (&Sprocess_contact);
7690 defsubr (&Sprocess_plist);
7691 defsubr (&Sset_process_plist);
7692 defsubr (&Slist_processes);
7693 defsubr (&Sprocess_list);
7694 defsubr (&Sstart_process);
7695 #ifdef HAVE_SERIAL
7696 defsubr (&Sserial_process_configure);
7697 defsubr (&Smake_serial_process);
7698 #endif /* HAVE_SERIAL */
7699 #ifdef HAVE_SOCKETS
7700 defsubr (&Sset_network_process_option);
7701 defsubr (&Smake_network_process);
7702 defsubr (&Sformat_network_address);
7703 #endif /* HAVE_SOCKETS */
7704 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7705 #ifdef SIOCGIFCONF
7706 defsubr (&Snetwork_interface_list);
7707 #endif
7708 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7709 defsubr (&Snetwork_interface_info);
7710 #endif
7711 #endif /* HAVE_SOCKETS ... */
7712 #ifdef DATAGRAM_SOCKETS
7713 defsubr (&Sprocess_datagram_address);
7714 defsubr (&Sset_process_datagram_address);
7715 #endif
7716 defsubr (&Saccept_process_output);
7717 defsubr (&Sprocess_send_region);
7718 defsubr (&Sprocess_send_string);
7719 defsubr (&Sinterrupt_process);
7720 defsubr (&Skill_process);
7721 defsubr (&Squit_process);
7722 defsubr (&Sstop_process);
7723 defsubr (&Scontinue_process);
7724 defsubr (&Sprocess_running_child_p);
7725 defsubr (&Sprocess_send_eof);
7726 defsubr (&Ssignal_process);
7727 defsubr (&Swaiting_for_user_input_p);
7728 defsubr (&Sprocess_type);
7729 defsubr (&Sset_process_coding_system);
7730 defsubr (&Sprocess_coding_system);
7731 defsubr (&Sset_process_filter_multibyte);
7732 defsubr (&Sprocess_filter_multibyte_p);
7733 defsubr (&Slist_system_processes);
7734 defsubr (&Sprocess_attributes);
7735 }
7736
7737 \f
7738 #else /* not subprocesses */
7739
7740 #include <sys/types.h>
7741 #include <errno.h>
7742 #include <sys/stat.h>
7743 #include <stdlib.h>
7744 #include <fcntl.h>
7745 #include <setjmp.h>
7746 #ifdef HAVE_UNISTD_H
7747 #include <unistd.h>
7748 #endif
7749
7750 #include "lisp.h"
7751 #include "systime.h"
7752 #include "character.h"
7753 #include "coding.h"
7754 #include "termopts.h"
7755 #include "sysselect.h"
7756
7757 extern int frame_garbaged;
7758
7759 extern EMACS_TIME timer_check ();
7760 extern int timers_run;
7761
7762 Lisp_Object QCtype, QCname;
7763
7764 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
7765 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
7766 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
7767 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
7768
7769 /* As described above, except assuming that there are no subprocesses:
7770
7771 Wait for timeout to elapse and/or keyboard input to be available.
7772
7773 time_limit is:
7774 timeout in seconds, or
7775 zero for no limit, or
7776 -1 means gobble data immediately available but don't wait for any.
7777
7778 read_kbd is a Lisp_Object:
7779 0 to ignore keyboard input, or
7780 1 to return when input is available, or
7781 -1 means caller will actually read the input, so don't throw to
7782 the quit handler.
7783
7784 see full version for other parameters. We know that wait_proc will
7785 always be NULL, since `subprocesses' isn't defined.
7786
7787 do_display != 0 means redisplay should be done to show subprocess
7788 output that arrives.
7789
7790 Return true if we received input from any process. */
7791
7792 int
7793 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7794 wait_for_cell, wait_proc, just_wait_proc)
7795 int time_limit, microsecs, read_kbd, do_display;
7796 Lisp_Object wait_for_cell;
7797 struct Lisp_Process *wait_proc;
7798 int just_wait_proc;
7799 {
7800 register int nfds;
7801 EMACS_TIME end_time, timeout;
7802 SELECT_TYPE waitchannels;
7803 int xerrno;
7804
7805 /* What does time_limit really mean? */
7806 if (time_limit || microsecs)
7807 {
7808 EMACS_GET_TIME (end_time);
7809 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7810 EMACS_ADD_TIME (end_time, end_time, timeout);
7811 }
7812
7813 /* Turn off periodic alarms (in case they are in use)
7814 and then turn off any other atimers,
7815 because the select emulator uses alarms. */
7816 stop_polling ();
7817 turn_on_atimers (0);
7818
7819 while (1)
7820 {
7821 int timeout_reduced_for_timers = 0;
7822
7823 /* If calling from keyboard input, do not quit
7824 since we want to return C-g as an input character.
7825 Otherwise, do pending quit if requested. */
7826 if (read_kbd >= 0)
7827 QUIT;
7828
7829 /* Exit now if the cell we're waiting for became non-nil. */
7830 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7831 break;
7832
7833 /* Compute time from now till when time limit is up */
7834 /* Exit if already run out */
7835 if (time_limit == -1)
7836 {
7837 /* -1 specified for timeout means
7838 gobble output available now
7839 but don't wait at all. */
7840
7841 EMACS_SET_SECS_USECS (timeout, 0, 0);
7842 }
7843 else if (time_limit || microsecs)
7844 {
7845 EMACS_GET_TIME (timeout);
7846 EMACS_SUB_TIME (timeout, end_time, timeout);
7847 if (EMACS_TIME_NEG_P (timeout))
7848 break;
7849 }
7850 else
7851 {
7852 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7853 }
7854
7855 /* If our caller will not immediately handle keyboard events,
7856 run timer events directly.
7857 (Callers that will immediately read keyboard events
7858 call timer_delay on their own.) */
7859 if (NILP (wait_for_cell))
7860 {
7861 EMACS_TIME timer_delay;
7862
7863 do
7864 {
7865 int old_timers_run = timers_run;
7866 timer_delay = timer_check (1);
7867 if (timers_run != old_timers_run && do_display)
7868 /* We must retry, since a timer may have requeued itself
7869 and that could alter the time delay. */
7870 redisplay_preserve_echo_area (14);
7871 else
7872 break;
7873 }
7874 while (!detect_input_pending ());
7875
7876 /* If there is unread keyboard input, also return. */
7877 if (read_kbd != 0
7878 && requeued_events_pending_p ())
7879 break;
7880
7881 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7882 {
7883 EMACS_TIME difference;
7884 EMACS_SUB_TIME (difference, timer_delay, timeout);
7885 if (EMACS_TIME_NEG_P (difference))
7886 {
7887 timeout = timer_delay;
7888 timeout_reduced_for_timers = 1;
7889 }
7890 }
7891 }
7892
7893 /* Cause C-g and alarm signals to take immediate action,
7894 and cause input available signals to zero out timeout. */
7895 if (read_kbd < 0)
7896 set_waiting_for_input (&timeout);
7897
7898 /* Wait till there is something to do. */
7899
7900 if (! read_kbd && NILP (wait_for_cell))
7901 FD_ZERO (&waitchannels);
7902 else
7903 FD_SET (0, &waitchannels);
7904
7905 /* If a frame has been newly mapped and needs updating,
7906 reprocess its display stuff. */
7907 if (frame_garbaged && do_display)
7908 {
7909 clear_waiting_for_input ();
7910 redisplay_preserve_echo_area (15);
7911 if (read_kbd < 0)
7912 set_waiting_for_input (&timeout);
7913 }
7914
7915 if (read_kbd && detect_input_pending ())
7916 {
7917 nfds = 0;
7918 FD_ZERO (&waitchannels);
7919 }
7920 else
7921 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7922 &timeout);
7923
7924 xerrno = errno;
7925
7926 /* Make C-g and alarm signals set flags again */
7927 clear_waiting_for_input ();
7928
7929 /* If we woke up due to SIGWINCH, actually change size now. */
7930 do_pending_window_change (0);
7931
7932 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7933 /* We waited the full specified time, so return now. */
7934 break;
7935
7936 if (nfds == -1)
7937 {
7938 /* If the system call was interrupted, then go around the
7939 loop again. */
7940 if (xerrno == EINTR)
7941 FD_ZERO (&waitchannels);
7942 else
7943 error ("select error: %s", emacs_strerror (xerrno));
7944 }
7945 #ifdef SOLARIS2
7946 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7947 /* System sometimes fails to deliver SIGIO. */
7948 kill (getpid (), SIGIO);
7949 #endif
7950 #ifdef SIGIO
7951 if (read_kbd && interrupt_input && (waitchannels & 1))
7952 kill (getpid (), SIGIO);
7953 #endif
7954
7955 /* Check for keyboard input */
7956
7957 if (read_kbd
7958 && detect_input_pending_run_timers (do_display))
7959 {
7960 swallow_events (do_display);
7961 if (detect_input_pending_run_timers (do_display))
7962 break;
7963 }
7964
7965 /* If there is unread keyboard input, also return. */
7966 if (read_kbd
7967 && requeued_events_pending_p ())
7968 break;
7969
7970 /* If wait_for_cell. check for keyboard input
7971 but don't run any timers.
7972 ??? (It seems wrong to me to check for keyboard
7973 input at all when wait_for_cell, but the code
7974 has been this way since July 1994.
7975 Try changing this after version 19.31.) */
7976 if (! NILP (wait_for_cell)
7977 && detect_input_pending ())
7978 {
7979 swallow_events (do_display);
7980 if (detect_input_pending ())
7981 break;
7982 }
7983
7984 /* Exit now if the cell we're waiting for became non-nil. */
7985 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7986 break;
7987 }
7988
7989 start_polling ();
7990
7991 return 0;
7992 }
7993
7994
7995 /* Don't confuse make-docfile by having two doc strings for this function.
7996 make-docfile does not pay attention to #if, for good reason! */
7997 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7998 0)
7999 (name)
8000 register Lisp_Object name;
8001 {
8002 return Qnil;
8003 }
8004
8005 /* Don't confuse make-docfile by having two doc strings for this function.
8006 make-docfile does not pay attention to #if, for good reason! */
8007 DEFUN ("process-inherit-coding-system-flag",
8008 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
8009 1, 1, 0,
8010 0)
8011 (process)
8012 register Lisp_Object process;
8013 {
8014 /* Ignore the argument and return the value of
8015 inherit-process-coding-system. */
8016 return inherit_process_coding_system ? Qt : Qnil;
8017 }
8018
8019 /* Kill all processes associated with `buffer'.
8020 If `buffer' is nil, kill all processes.
8021 Since we have no subprocesses, this does nothing. */
8022
8023 void
8024 kill_buffer_processes (buffer)
8025 Lisp_Object buffer;
8026 {
8027 }
8028
8029 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
8030 0, 0, 0,
8031 doc: /* Return a list of numerical process IDs of all running processes.
8032 If this functionality is unsupported, return nil.
8033
8034 See `process-attributes' for getting attributes of a process given its ID. */)
8035 ()
8036 {
8037 return list_system_processes ();
8038 }
8039
8040 DEFUN ("process-attributes", Fprocess_attributes,
8041 Sprocess_attributes, 1, 1, 0,
8042 doc: /* Return attributes of the process given by its PID, a number.
8043
8044 Value is an alist where each element is a cons cell of the form
8045
8046 \(KEY . VALUE)
8047
8048 If this functionality is unsupported, the value is nil.
8049
8050 See `list-system-processes' for getting a list of all process IDs.
8051
8052 The KEYs of the attributes that this function may return are listed
8053 below, together with the type of the associated VALUE (in parentheses).
8054 Not all platforms support all of these attributes; unsupported
8055 attributes will not appear in the returned alist.
8056 Unless explicitly indicated otherwise, numbers can have either
8057 integer or floating point values.
8058
8059 euid -- Effective user User ID of the process (number)
8060 user -- User name corresponding to euid (string)
8061 egid -- Effective user Group ID of the process (number)
8062 group -- Group name corresponding to egid (string)
8063 comm -- Command name (executable name only) (string)
8064 state -- Process state code, such as "S", "R", or "T" (string)
8065 ppid -- Parent process ID (number)
8066 pgrp -- Process group ID (number)
8067 sess -- Session ID, i.e. process ID of session leader (number)
8068 ttname -- Controlling tty name (string)
8069 tpgid -- ID of foreground process group on the process's tty (number)
8070 minflt -- number of minor page faults (number)
8071 majflt -- number of major page faults (number)
8072 cminflt -- cumulative number of minor page faults (number)
8073 cmajflt -- cumulative number of major page faults (number)
8074 utime -- user time used by the process, in the (HIGH LOW USEC) format
8075 stime -- system time used by the process, in the (HIGH LOW USEC) format
8076 time -- sum of utime and stime, in the (HIGH LOW USEC) format
8077 cutime -- user time used by the process and its children, (HIGH LOW USEC)
8078 cstime -- system time used by the process and its children, (HIGH LOW USEC)
8079 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
8080 pri -- priority of the process (number)
8081 nice -- nice value of the process (number)
8082 thcount -- process thread count (number)
8083 start -- time the process started, in the (HIGH LOW USEC) format
8084 vsize -- virtual memory size of the process in KB's (number)
8085 rss -- resident set size of the process in KB's (number)
8086 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
8087 pcpu -- percents of CPU time used by the process (floating-point number)
8088 pmem -- percents of total physical memory used by process's resident set
8089 (floating-point number)
8090 args -- command line which invoked the process (string). */)
8091 (pid)
8092
8093 Lisp_Object pid;
8094 {
8095 return system_process_attributes (pid);
8096 }
8097
8098 void
8099 init_process ()
8100 {
8101 kbd_is_on_hold = 0;
8102 }
8103
8104 void
8105 syms_of_process ()
8106 {
8107 QCtype = intern_c_string (":type");
8108 staticpro (&QCtype);
8109 QCname = intern_c_string (":name");
8110 staticpro (&QCname);
8111 QCtype = intern_c_string (":type");
8112 staticpro (&QCtype);
8113 QCname = intern_c_string (":name");
8114 staticpro (&QCname);
8115 Qeuid = intern_c_string ("euid");
8116 staticpro (&Qeuid);
8117 Qegid = intern_c_string ("egid");
8118 staticpro (&Qegid);
8119 Quser = intern_c_string ("user");
8120 staticpro (&Quser);
8121 Qgroup = intern_c_string ("group");
8122 staticpro (&Qgroup);
8123 Qcomm = intern_c_string ("comm");
8124 staticpro (&Qcomm);
8125 Qstate = intern_c_string ("state");
8126 staticpro (&Qstate);
8127 Qppid = intern_c_string ("ppid");
8128 staticpro (&Qppid);
8129 Qpgrp = intern_c_string ("pgrp");
8130 staticpro (&Qpgrp);
8131 Qsess = intern_c_string ("sess");
8132 staticpro (&Qsess);
8133 Qttname = intern_c_string ("ttname");
8134 staticpro (&Qttname);
8135 Qtpgid = intern_c_string ("tpgid");
8136 staticpro (&Qtpgid);
8137 Qminflt = intern_c_string ("minflt");
8138 staticpro (&Qminflt);
8139 Qmajflt = intern_c_string ("majflt");
8140 staticpro (&Qmajflt);
8141 Qcminflt = intern_c_string ("cminflt");
8142 staticpro (&Qcminflt);
8143 Qcmajflt = intern_c_string ("cmajflt");
8144 staticpro (&Qcmajflt);
8145 Qutime = intern_c_string ("utime");
8146 staticpro (&Qutime);
8147 Qstime = intern_c_string ("stime");
8148 staticpro (&Qstime);
8149 Qtime = intern_c_string ("time");
8150 staticpro (&Qtime);
8151 Qcutime = intern_c_string ("cutime");
8152 staticpro (&Qcutime);
8153 Qcstime = intern_c_string ("cstime");
8154 staticpro (&Qcstime);
8155 Qctime = intern_c_string ("ctime");
8156 staticpro (&Qctime);
8157 Qpri = intern_c_string ("pri");
8158 staticpro (&Qpri);
8159 Qnice = intern_c_string ("nice");
8160 staticpro (&Qnice);
8161 Qthcount = intern_c_string ("thcount");
8162 staticpro (&Qthcount);
8163 Qstart = intern_c_string ("start");
8164 staticpro (&Qstart);
8165 Qvsize = intern_c_string ("vsize");
8166 staticpro (&Qvsize);
8167 Qrss = intern_c_string ("rss");
8168 staticpro (&Qrss);
8169 Qetime = intern_c_string ("etime");
8170 staticpro (&Qetime);
8171 Qpcpu = intern_c_string ("pcpu");
8172 staticpro (&Qpcpu);
8173 Qpmem = intern_c_string ("pmem");
8174 staticpro (&Qpmem);
8175 Qargs = intern_c_string ("args");
8176 staticpro (&Qargs);
8177
8178 defsubr (&Sget_buffer_process);
8179 defsubr (&Sprocess_inherit_coding_system_flag);
8180 defsubr (&Slist_system_processes);
8181 defsubr (&Sprocess_attributes);
8182 }
8183
8184 \f
8185 #endif /* not subprocesses */
8186
8187 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
8188 (do not change this comment) */