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