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